简体   繁体   English

setTimeout似乎执行得太快

[英]setTimeout appears to execute too fast

I've been fiddling around with setTimeout and setInterval, and I cannot get the code to execute the way I would like it to. 我一直在使用setTimeout和setInterval,我无法让代码按照我希望的方式执行。 My goal is to create a setInterval, which calls once every three seconds, and have it clear after ten seconds. 我的目标是创建一个setInterval,每隔三秒调用一次,并在十秒后清除它。 However, when I run the code in firebug, the only thing I get is a number, which I assume is the id of setInterval because every time I execute the code, the number increases. 但是,当我在firebug中运行代码时,我唯一得到的是一个数字,我假设它是setInterval的id,因为每次执行代码时,数字都会增加。

var intID = setInterval(function() {
    console.log("I've been called");},3000);


setTimeout(clearInterval(intID), 10000);

This statement: 这个说法:

setTimeout(clearInterval(intID), 10000);

means, "call the function 'clearInterval' passing the value of variable 'intID', and then pass the return value of that and the number 10000 to the function 'setTimeout'." 表示“调用函数'clearInterval'传递变量'intID'的值,然后将返回值和数字10000传递给函数'setTimeout'。”

In other words, you're calling the function "clearInterval" and then passing the returned value to setTimeout() . 换句话说,您正在调用函数“clearInterval”,然后将返回的值传递给setTimeout()

Instead, pass setTimeout() a function: 相反,传递setTimeout()函数:

setTimeout(function() { clearInterval(intID); }, 10000);

You are not setting up the interval like this: 没有像这样设置间隔:

setInterval(console.log("I've been called"), 3000);

If you did, console.log would be called immediately -- even before setInterval , since it's an argument to setInterval and arguments have to be evaluated before calling the function that uses them. 如果你这样做,则会立即调用console.log - 甚至 setInterval 之前 ,因为它是setInterval的参数,并且必须在调用使用它们的函数之前评估参数。

So why are you setting up the timeout like this ? 你为什么要像这样设置超时

setTimeout(clearInterval(intID), 10000);

This causes the exact same kind of problem as above. 这导致与上述完全相同的问题。

Just do the same thing you did when setting up the interval instead: 只需执行设置间隔时所做的相同操作:

setTimeout(function() { clearInterval(intID); }, 10000);

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

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