1

settimeout第三个参数

 2 years ago
source link: https://www.fly63.com/article/detial/12135
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

更新日期: 2022-09-16阅读: 65标签: 参数分享

扫一扫分享

说起来你可能不相信,setTimeout居然有第三个参数,我以前也没用过这个,是前几天看别人博客发现的,咋一看还以为写错了吧,下面一起看看这个setTimeout第三个参数。

setTimeout

setTimeout()方法设置一个定时器,该定时器在定时器到期后执行一个函数或指定的一段代码语法如下:

var timeoutID = scope.setTimeout(function[, delay, arg1, arg2, ...]);
var timeoutID = scope.setTimeout(function[, delay]);
var timeoutID = scope.setTimeout(code[, delay]);

setTimeout函数有三个参数

fn:(必传)需要执行的函数。
time:(非必传)

延迟的毫秒数  。

  • 传值时:倒计时time毫秒后执行fn;
  • 不传时:默认为0,fn在最早可得的空闲时间执行,在"任务队列"的尾部执行fn,因此要等到同步任务和"任务队列"现有的事件都处理完,才会得到执行。

param:(非必传)

附加参数,一旦定时器到期,它们会作为参数传递给。

我们可以知道定时器启动的时候,第三个及以后的参数会作为第一个 func()的参数传进去。

一起来看个经典的栗子吧:

for (var i = 0; i < 5; i++) {
  setTimeout(function () {
    console.log(i);
  }, 1000);
}

上面这个栗子,大家都知道会连续输出 5 个 5,因为 setTimeout 是一个异步操作,而等到执行 setTimeout 时,for 循环已经执行完毕,这时的 i 已经等于 5,所以输出 5 次 5。当然,这并不是我们想要的。

最常见的改进方案是使用闭包。通过闭包,可以将变量 i 驻留在内存中,当输出 j 时,引用的是外部函数传递的变量 i,这个 i 是根据循环来的,执行 setTimeout 时已经确定了里面 i 的值,进而确定了 j 的值。

for (var i = 0; i < 5; i++) {
  (function (j) {
    setTimeout(function () {
      console.log(j);
    }, j * 1000);
  })(i);
}

运用 setTimeout 的第三个参数。由于每次传入的参数是从 for 循环里面取到的值,所以会依次输出 0~4。

for (var i = 0; i < 5; i++) {
  setTimeout(
    function (j) {
      console.log(j);
    },
    i * 1000,
    i
  );
}

这个用例的使用场景不常见,但可以对 setTimeout 有进一步的了解。

var doc = document.getElementById("div");
setTimeout(
  function () {
    doc.style.color = "red";
  },
  10000,
  setTimeout(function () {
    doc.style.color = "black";
  }, 5000)
);

上面的结果是,div 元素内的字体样式 5 秒后变黑,10 秒后再变红。

链接: https://www.fly63.com/article/detial/12135


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK