我想传递变量 setTimeout 函数并对其执行某些操作。当我提醒 i 的值时,它会显示我没想到的数字。我做错了什么?我想要从1到8的日志值。
I want to pass variable setTimeoutfunction and do something with that. When I alert value of i it shows me numbers that i did not expected. What i m doing wrong? I want log values from 1 till 8.
var end=8; for (var i = 1; i < end; i ++) { setTimeout(function (i) { console.log(i); }, 800); }推荐答案
解决此问题的标准方法是使用工厂函数:
The standard way to solve this is to use a factory function:
var end=8; for (var i = 1; i < end; i ++) { setTimeout(makeResponder(i), 800); } function makeResponder(index) { return function () { console.log(index); }; }实例 | 来源
在那里,我们致电 makeResponder 在循环中,它返回一个函数,该函数关闭传递给它的参数( index )而不是 i 变量。 (这很重要。如果您刚从匿名函数中删除 i 参数,您的代码将部分工作,但所有函数都会看到我当他们跑时,而不是他们最初安排时;在你的例子中,他们都看到 8 。)
There, we call makeResponder in the loop, and it returns a function that closes over the argument passed into it (index) rather than the i variable. (Which is important. If you just removed the i argument from your anonymous function, your code would partially work, but all of the functions would see the value of i as of when they ran, not when they were initially scheduled; in your example, they'd all see 8.)
更新来自您的评论:
...如果我以这种方式调用它将是正确的 setTimeout(makeResponder(i),i * 800); ?
是的,如果您的目标是让每次通话比最后一次大约晚800毫秒发生,那么工作:
Yes, if your goal is to have each call occur roughly 800ms later than the last one, that will work:
实例 来源
我试过 setTimeout(makeResponder(i),setInterval(i)); function setInterval(index){console.log(index * 800);返回索引* 800; } 但它无法正常工作
您不使用 setInterval 这样,可能根本不想用它。
You don't use setInterval that way, and probably don't want to use it for this at all.
进一步更新:您在下面说过:
我需要先迭代打印8延迟8秒,第二次迭代打印7延迟7秒........打印2延迟2秒...打印0延迟0秒
I need first iteration print 8 delay 8 sec, second iteration print 7 delay 7 sec ........print 2 delay 2 sec ...print 0 delay 0 sec.
你刚才使用第二次超时再次应用上述原则:
You just apply the principles above again, using a second timeout:
var end=8; for (var i = 1; i < end; i ++) { setTimeout(makeResponder(i), i * 800); } function makeResponder(index) { return function () { var thisStart = new Date(); console.log("index = " + index + ", first function triggered"); setTimeout(function() { console.log("index = " + index + ", second function triggered after a further " + (new Date() - thisStart) + "ms delay"); }, index * 1000); }; }实例 | 来源
我想你现在有了你需要的所有工具。
I think you now have all the tools you need to take this forward.
更多推荐
如何将变量传递给匿名函数
发布评论