JS:尝试使用增量值setTimeout
JS: trying to use setTimeout with incremental values
本文关键字:setTimeout JS 更新时间:2023-09-26
我试图在函数调用中使用增量id在循环上设置一些延迟,以及增量较大的延迟时间。我的设置是这样的:
var delay = 0;
var delayMilliseconds = 250;
timeOutArray = [];
for(var i=0; i<100; i++){
delay = i*delayMilliseconds;
timeOutArray[i] = setTimeout(function(){
loadRoute(modelsArray[i], (i+1));
},delay);
}
我遇到的问题是,在任何loadRoute()函数被调用时,被引用的"I"已经被增加到99。
我正在寻找一种方法,使它在我设置超时的那一刻识别"I"的数量,而不是超时发生的那一刻。
我找到了这篇关于使用"promises"的文章,但是它有点令人困惑。Javascript -等待使用setTimeout
的函数的真正结束有人可以告诉我知道在这些调用中实现承诺,或者任何可以在eval()中不包装setTimeout代码的情况下做到这一点吗?
这是您的代码的工作示例。问题是对Scope & .
var delay = 0;
var delayMilliseconds = 250;
timeOutArray = [];
for (var i=1; i<100; i++) {
(function(j){
delay = j*delayMilliseconds;
timeOutArray[j] = setTimeout(function(){
console.log(j)
//loadRoute(modelsArray[j], (j+1));
},delay);
})( i );
}
解释:
(function(j){
//this part of the code create new scope
})( i );
在每次迭代中使用上面的函数为每次迭代创建一个新作用域,这使timeout函数回调有机会为每次迭代关闭一个新的作用域,该作用域中有一个变量,该变量具有正确的每次迭代值供我们访问。
来源-更多信息
保存在闭包中,以保留原始值。
timeOutArray[i] = setTimeout( (function(i) { return function(){
loadRoute(modelsArray[i], (i+1));
}) (i),delay);
基本上,您在每个循环迭代中创建并执行一个新的匿名函数,并将当前i
的副本传递给它。在执行时,此函数返回另一个匿名函数,然后将该函数传递给setTimeout
。然而,这个函数保留了对创建它的作用域的引用,因此看到i
是由外部匿名函数保存的。
这有点棘手。
或者在for循环之外定义超时函数并调用它:
var delay = 0;
var delayMilliseconds = 250;
function doTimeoutStuff(i, delay) {
setTimeout(function () {
loadRoute(modelsArray[i], (i+1));
}, delay);
}
for (var i=0; i<5; i++) {
delay = i*delayMilliseconds;
doTimeoutStuff(i, delay);
}
不创建闭包,setTimeout()
允许您在执行时将变量传递给回调函数,然后在回调期间内驻留。
setTimeout(function[, delay, arg1, arg2, ...]);
来源:MDN - setTimeout
相关文章:
- JS:setTimeout函数的UI计数
- JS-我的循环使用setTimeout停止循环
- Node.js setTimeout在系统时间更改后未触发
- 延迟后JS setTimeout获取事件
- SetTimeOut() in THREE JS
- js:无法将参数传递给setTimeOut中的匿名函数
- 跨Node.js重新启动持久化setTimeout和setInterval
- 只有setTimeout执行函数.JS
- Node.js-有没有一种方法可以访问传递给'setTimeout'使用返回的timeoutObject
- 如何使用js-setTimeout延迟此文本的淡入
- 在书签中使用 JS setTimeout
- 使用 setTimeout 在 js 中使用 Promise 的重复函数
- setTimeout() 如何在 JS 上工作
- js setTimeout recursion return-continue
- JS setTimeout() alternative
- 在 setTimeout() 回调完成后执行 JS 代码
- 在 Backbone.js 中的模型中使用 setTimeout
- 重写require.js中的setTimeout
- .js setTimeout代码不起作用
- 动画淡入淡出|jQuery与纯js|setInterval与setTimeout