DEV Community

NikiMunger
NikiMunger

Posted on

setInterval()、setTimeout()

setInterval()

setInterval() 是 JavaScript 中用来 每隔固定时间重复执行某段代码 的定时器函数。

基本语法

const timerId = setInterval(callback, delay, arg1, arg2, ...);
Enter fullscreen mode Exit fullscreen mode

参数说明

  • callback:要重复执行的函数
  • delay:每次执行之间的时间间隔(毫秒)
  • arg1, arg2, ...(可选):会作为参数传给 callback

返回值

  • timerId:一个唯一 ID,用于取消定时器(用于 clearInterval)。

示例

const id = setInterval(() => {
  console.log('running...');
}, 1000);

setTimeout(() => {
  clearInterval(id); // 3秒后停止
  console.log('stopped');
}, 3000);
Enter fullscreen mode Exit fullscreen mode

clearInterval(id):清除定时器


setTimeout()

JavaScript 中用于“延迟执行某一段代码”的定时器。
只执行一次
如果需要重复执行,应使用 setInterval 或用递归的 setTimeout 来模拟。

基本语法

const timerId = setTimeout(callback, delay, arg1, arg2, ...);
Enter fullscreen mode Exit fullscreen mode

参数说明

  • callback:需要延迟执行的函数
  • delay:延迟时间(毫秒)
  • arg1、arg2...:可选,传给 callback 的参数

返回值

  • 一个 timerId,用于取消定时器(clearTimeout)

示例

const id = setTimeout(() => {
  console.log("不会执行");
}, 5000);

clearTimeout(id); // 清除定时器
Enter fullscreen mode Exit fullscreen mode

Top comments (0)