如何将变量传递给setTimeout函数?

编程入门 行业动态 更新时间:2024-10-28 14:24:42
本文介绍了如何将变量传递给setTimeout函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试设置五个交错的函数调用(相隔一秒发生)。那部分工作正常。什么行不通,我不能将值0到4传递给回调函数。它每次只传递'5'。我似乎无法弄清楚为什么以及如何解决它。

I'm trying to set five staggered function calls (happening one second apart). That part works fine. What doesn't work is, I can't pass values 0 through 4 into the callback function. It just passes '5' each time. I can't seem to figure out why and how to fix it.

代码:

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

结果:

5 5 5 5 5

所需结果:

0 1 2 3 4

推荐答案

那是因为你创建了一个闭包。因此,传递给 setTimeout 的函数共享相同的 i 实例。在支持标准(不是IE)的浏览器中,您可以:

That's because you create a closure. So the function you pass to setTimeout share the same i instances. In the browser that supports the standards (not IE) you could have:

setTimeout(callback, loadDelay, i);

参见: www.whatwg/specs/web-apps/current-work/multipage/timers.html#计时器

否则你必须实际 bind 该函数的参数:

Otherwise you have to actually bind the argument to the function:

setTimeout(callback.bind(undefined, i), loadDelay);

请参阅: developer.mozilla/en/JavaScript/Reference/Global_Objects/Function/bind

如果浏览器不支持ES5 bind 方法,您可以实现上面链接中的垫片,也可以手动执行以下操作:

If the browser doesn't support ES5 bind method, you can either implement the shim present in the link above, or manually doing something like:

setTimeout(function(index){ return function() { callback(index) } }(i), loadDelay);

但我会说使用 bind 并且值得实施垫片。您实际上可以使用它: github/kriskowal/es5-shim

But I would say it's more readable using bind and it's worthy to implement the shim. You can actually use this: github/kriskowal/es5-shim

在本地不支持es5的浏览器中添加es5功能(尽可能)。

To add es5 capabilities (where is possible) in the browser that don't support es5 natively.

更多推荐

如何将变量传递给setTimeout函数?

本文发布于:2023-11-23 18:12:18,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1622411.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:变量   如何将   函数   setTimeout

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!