[英]arguments to javascript callback function
var data = [{offset: 2000, str:'foo'}, {offset: 4000, str:'bar'}];
for (var i=0; i<data.length; i++) {
var x = data[i];
setTimeout(function(){printStuff(x.str)}, x.offset);
}
function printStuff(str) {
console.log(str);
}
I was expecting to get printStuff('foo')
at 2000 ms offset and printStuff('bar')
at 4000 ms offset but instead it prints 'bar' both times. 我原本希望在2000毫秒偏移量时获得printStuff('foo')
而在4000毫秒偏移量时获得printStuff('bar')
,但它两次都打印'bar'。 I've no idea what's going on, help please. 我不知道发生了什么事,请帮忙。
Do this : 做这个 :
for (var i = 0; i < data.length; i++) {
(function (x) {
setTimeout(function () {
printStuff(x.str)
}, x.offset);
})(data[i]);
}
Your problem is that x has changed in the closure when the function is called. 您的问题是在调用函数时x在闭包中已更改。
setTimeout
不会阻止代码继续执行,因此循环完成,并且在执行setTimeout
回调时,“ x”的最新值是data
数组中的第二个对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.