setTimeout似乎执行得太快 [英] setTimeout appears to execute too fast
问题描述
我一直在使用setTimeout和setInterval,我无法让代码按照我希望的方式执行。我的目标是创建一个setInterval,每隔三秒调用一次,并在十秒后清除它。但是,当我在firebug中运行代码时,我唯一得到的是一个数字,我假设它是setInterval的id,因为每次执行代码时,数字都会增加。
I've been fiddling around with setTimeout and setInterval, and I cannot get the code to execute the way I would like it to. My goal is to create a setInterval, which calls once every three seconds, and have it clear after ten seconds. 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.
var intID = setInterval(function() {
console.log("I've been called");},3000);
setTimeout(clearInterval(intID), 10000);
推荐答案
此声明:
setTimeout(clearInterval(intID), 10000);
表示调用函数'clearInterval'传递变量'intID'的值,然后传递它的返回值和数字 10000
到函数'setTimeout'。
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,然后将返回的值传递给 setTimeout()
。
In other words, you're calling the function "clearInterval" and then passing the returned value to setTimeout()
.
相反,传递 setTimeout()
一个函数:
setTimeout(function() { clearInterval(intID); }, 10000);
这篇关于setTimeout似乎执行得太快的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!