简体   繁体   English

在setTimeout中将参数传递给函数

[英]Passing parameters to the function in setTimeout

I want to call a function in a cycle with setTimeout() , and also pass the counter as a parameter. 我想用setTimeout()循环调用一个函数,并将计数器作为参数传递。 Here's what I tried: 这是我尝试过的:

<!DOCTYPE html>
<html><body>

<button onclick="timed1()">Display alerts</button>

<script>
function timed1() {
 for (i=1; i<4; i++){
  setTimeout(
     (function(i){ alert(i) })(i), 1000*i
   );
 }
}
</script>

</body></html>

Function calls are done with correct values, but immediately instead of the intervals I wanted. 函数调用以正确的值完成,但立即而不是我想要的间隔。 I have read this and this SO questions but unfortunately don't see yet what should I change in my case. 我已阅读 SO问题,但遗憾的是没有看到什么还我应该在我的情况下更改。

You can use let here if you want to bind different values of i to the setTimeout function 如果要将i不同值绑定到setTimeout函数,可以在这里使用let

 function timed1() { for (let i=1; i<4; i++){ setTimeout(function() { alert(i) }, 1000*i) } } timed1() 

The expression (function(i){ alert(i) })(i) does not return a function for setTimeout to call. 表达式(function(i){ alert(i) })(i)不返回setTimeout调用的函数。 If you're going the IIFE way, make sure to return a new function from it: 如果要使用IIFE ,请确保从中返回一个新函数:

setTimeout((function(i) {
    return function() {
        alert(i);
    };
})(i), 1000 * i);

With ES2015+ a far better readable equivalent can be realized: 使用ES2015 +,可以实现更好的可读性:

for (let i = 1; i < 4; i++) {
    setTimeout(() => alert(i), 1000 * i);
}

You're swimming on IIFE (Immediately Invoked Function Expression). 您正在使用IIFE (立即调用函数表达式)。

You're calling your function immediately. 您正在立即调用函数。

setTimeout(
   (function(i){ alert(i) })(i), 1000*i
);                           ^

The scope of your variable i is open, you need to use let keyword. 您的变量i的范围是开放的,您需要使用let关键字。

for (i = 1; i < 4; i++) {
     ^

Look at this code snippet 看看这个代码片段

 function timed1() { for (let i = 1; i < 4; i++) { setTimeout( function() { alert(i) }, 1000 * i); } } 
 <button onclick="timed1()">Display alerts</button> 

The setTimeout function allows you to pass arguments to the callback function, like so: setTimeout函数允许您将参数传递给回调函数,如下所示:

 function timed1() { for (i=1; i<4; i++){ setTimeout(alert, 1000 * i, i); } } timed1() 

Any arguments after the time are passed along to the callback. 时间之后的所有参数都传递给回调。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM