js实现定时执行
定时执行的方法
在JavaScript中,可以通过多种方式实现定时执行代码的功能。以下是常见的几种方法:
setTimeout
setTimeout用于在指定的时间后执行一次函数。它接受两个参数:回调函数和延迟时间(毫秒)。

setTimeout(function() {
console.log('This will run after 2 seconds');
}, 2000);
setInterval
setInterval用于每隔指定的时间重复执行函数。它接受两个参数:回调函数和间隔时间(毫秒)。
setInterval(function() {
console.log('This will run every 1 second');
}, 1000);
clearTimeout和clearInterval
如果需要取消定时任务,可以使用clearTimeout或clearInterval,传入定时器的ID。

const timerId = setTimeout(() => {}, 2000);
clearTimeout(timerId);
const intervalId = setInterval(() => {}, 1000);
clearInterval(intervalId);
requestAnimationFrame
requestAnimationFrame用于在浏览器下一次重绘之前执行回调函数,适合动画或高频次更新的场景。
function animate() {
console.log('Animation frame');
requestAnimationFrame(animate);
}
requestAnimationFrame(animate);
Promise和async/await
通过Promise和async/await可以实现更灵活的定时控制。
function delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function run() {
await delay(2000);
console.log('Delayed execution');
}
run();
注意事项
- 避免在
setInterval中使用耗时操作,可能导致任务堆积。 - 使用
requestAnimationFrame时注意性能优化,避免不必要的计算。 - 在Node.js环境中,还可以使用
setImmediate或process.nextTick实现类似功能。






