js实现定时执行
使用 setTimeout 实现单次延迟执行
setTimeout(() => {
// 需要执行的代码
console.log('延迟执行');
}, 1000); // 1000毫秒后执行
使用 setInterval 实现循环定时执行
const intervalId = setInterval(() => {
// 需要循环执行的代码
console.log('每隔1秒执行一次');
}, 1000);
// 清除定时器
// clearInterval(intervalId);
使用 requestAnimationFrame 实现高性能动画定时
function animate() {
// 动画逻辑代码
console.log('动画帧执行');
// 循环调用
requestAnimationFrame(animate);
}
// 启动动画
requestAnimationFrame(animate);
使用 Promise 和 async/await 实现定时控制
function delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function timedExecution() {
await delay(1000);
console.log('1秒后执行');
await delay(2000);
console.log('再2秒后执行');
}
timedExecution();
使用 Web Worker 实现后台定时任务
worker.js:
let timer;
self.onmessage = function(e) {
if (e.data === 'start') {
timer = setInterval(() => {
self.postMessage('tick');
}, 1000);
} else if (e.data === 'stop') {
clearInterval(timer);
}
};
主线程:

const worker = new Worker('worker.js');
worker.onmessage = (e) => {
if (e.data === 'tick') {
console.log('Worker定时消息');
}
};
// 启动Worker定时器
worker.postMessage('start');
// 停止Worker定时器
// worker.postMessage('stop');
使用 Date 对象实现精确计时
function preciseTimer(callback, interval) {
let expected = Date.now() + interval;
function tick() {
const drift = Date.now() - expected;
callback();
expected += interval;
setTimeout(tick, Math.max(0, interval - drift));
}
setTimeout(tick, interval);
}
preciseTimer(() => {
console.log('精确计时执行');
}, 1000);






