javascript 如何将参数传递给setTimeout函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17080318/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 07:01:36  来源:igfitidea点击:

How to pass parameters to setTimeout function

javascriptsettimeout

提问by v09

I am relatively novice to javascript. I have written a simple counter program that starts count down from 10 till it reaches 1.

我对 javascript 比较陌生。我写了一个简单的计数器程序,它从 10 开始倒计时,直到达到 1。

  <script type="text/javascript">
    function countDown(secs) {
        var element = document.getElementById("status");
        element.innerHTML = "Please wait for "+secs+" seconds";
        if(secs < 1) {
            clearTimeout(timer);
            element.innerHTML = '<h2>Countdown Complete!</h2>';
            element.innerHTML += '<a href="#">Click here now</a>';
        }
        secs--;
 --->       **var timer = setTimeout('countDown('secs')',1000);**
    }
    </script>
    <div id="status"></div>
    <script type="text/javascript">countDown(10);</script>

Then I tried passing parameter as '+secs+'to the countDown function.

然后我尝试将参数传递'+secs+'给 countDown 函数。

var timer = setTimeout('countDown('+secs+')',1000);

Above change works.

以上更改有效。

My question is why should I need to pass parameter as '+secs+' and NOT only 'secs' ? What difference does it make?

我的问题是为什么我需要将参数作为 '+secs+' 而不仅仅是 'secs' 传递?它有什么区别?

回答by Arun P Johny

use

利用

var timer = setTimeout(function(){
        countDown(secs)
    },1000);

or

或者

var timer = setTimeout('countDown('  + secs + ')',1000);

In your case the problem was your were using string concatenation with a variable without +sign (my second example) with will cause a syntactical error

在您的情况下,问题是您使用字符串连接与没有+符号的变量(我的第二个示例)将导致语法错误

回答by jahroy

Your first attempt is a synax error:

您的第一次尝试是 Synax 错误:

var timer = setTimeout('countDown('secs')',1000);

You're trying to pass a string to setTimeout(which is a bad idea to begin with), but you're not creating the string properly.

您正在尝试将字符串传递给setTimeout(这是一个坏主意),但您没有正确创建字符串。

The single quotes around the word secsare not escaped, so you're actually passing the string literal countDown(followed by the variable secs, followed by the string literal ). Because there are no operators between the strings, this is invalid syntax.

单词周围的单引号secs不会被转义,因此您实际上传递的是字符串文字,countDown(后跟变量secs,然后是字符串文字)。因为字符串之间没有运算符,所以这是无效的语法。

However, when you use the +symbols, you're adding 3 strings together to create the method invocation you want (the+operator is used to concatenate strings in JavaScript):

但是,当您使用的+符号,你加入3串在一起来创建你想要的(方法调用+操作者使用JavaScript中连接字符串):

'countDown(' + 'secs' + ')' ===  'countDown(secs)'

The three strings added together create a string that contains valid JavaScript, so it can be passed to the setTimeout()function.

三个字符串加在一起创建了一个包含有效 JavaScript 的字符串,因此可以将其传递给setTimeout()函数。

Although you canpass a string to setTimeout(), the better approach is to pass a function reference.

尽管您可以将字符串传递给setTimeout(),但更好的方法是传递函数引用。

This is typically done with an anonymous function like this:

这通常是通过这样的匿名函数完成的:

setTimeout(function () {
    countDown(secs);
}, 1000);

If you don't need to pass a parameter, you can do this:

如果不需要传递参数,可以这样做:

function countDown() {
    alert("10... 9... 8...");
}

setTimeout(countDown, 1000);

Note that when a function reference is specified as a variable, you do not use the ()symbols. When you use parentheses after a function in JavaScript, the function is invoked.

请注意,将函数引用指定为变量时,不要使用()符号。当您在 JavaScript 中的函数后使用括号时,会调用该函数。

回答by senior

an easy way to do it using setTimeout:

使用 setTimeout 的一种简单方法:

setTimeout(FunctionName,delay,arg1,arg2....);

In your case you can simply do like that:

在您的情况下,您可以简单地这样做:

setTimeout(countDown,1000,secs);

I suggest this link: http://javascript.info/settimeout-setinterval

我建议这个链接:http: //javascript.info/settimeout-setinterval

回答by Ja?ck

Just write a closure to perform the decrement like so:

只需编写一个闭包来执行递减,如下所示:

if (secs < 1) {
    element.innerHTML = '<h2>Countdown Complete!</h2>';
    element.innerHTML += '<a href="#">Click here now</a>';
} else {
    // wait 1 second
    setTimeout(function() {
        countDown(secs - 1); // decrement and run ourselves again
    }, 1000);
}

I've also removed the clearTimeout()in favour of a simple elsecondition.

我还删除了clearTimeout()支持简单else条件的 。

回答by Aadit M Shah

The setTimeoutfunction allows you to pass additional parameters to the function. Hence you can rewrite your code as follows:

setTimeout函数允许您将附加参数传递给该函数。因此,您可以按如下方式重写代码:

var timer = setTimeout(countDown, 1000, secs);

It's supported in all major browsers except for some old versions of IE. See this question for more details: Why does Underscore.js have a delay function?

除了一些旧版本的 IE,所有主流浏览器都支持它。更多细节请看这个问题:为什么 Underscore.js 有延迟功能?

回答by Chris Kochel

Aadit had the right idea. I needed to start multiple timeouts within a loop, and they all ended up with the variable set to the same value. Here is a fiddle illustrating why the only method that works well asynchronously is Aadit's.

Aadit 的想法是正确的。我需要在一个循环中启动多个超时,它们最终都将变量设置为相同的值。这里有一个小提琴说明为什么异步工作良好的唯一方法是 Aadit 的。

http://jsfiddle.net/85fmwew4/

http://jsfiddle.net/85fmwew4/

for(i=0;i<10;i++){
    setTimeout(function(){bad(i)}, 1000)    // bad for async
    setTimeout(good, 1000, i)               // good for async
}

回答by Chris Scott

This is the only thing that worked for me (passing variables to setTimeout in node.js):

这是唯一对我有用的东西(将变量传递给 node.js 中的 setTimeout):

setTimeout(function(teamNum,zeroBase,position) {
    spawnAI(roomIndex, 'scout', teamNum, position);
}, timeToSpawn,teamNum,zeroBase,position);

回答by Damilola Olowookere

Now with recent javascript optimizations in modern browsers, you can simply do:

现在使用现代浏览器中最近的 javascript 优化,您可以简单地执行以下操作:

var timer = setTimeout( countDown( secs ) , 1000 );

var timer = setTimeout( countDown( secs ) , 1000 );