Javascript setTimeout 忽略超时?(立即开火)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4120781/
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
setTimeout ignores timeout? (Fires immediately)
提问by Jonah H.
This is my first real dive into JavaScript. Sure I've used it before, but I've never really written anything from scratch.
这是我第一次真正深入 JavaScript。当然我以前用过它,但我从来没有真正从头开始写过任何东西。
Anyway, I'm having a very strange problem that I hope someone can figure out for me.
无论如何,我遇到了一个非常奇怪的问题,希望有人能帮我解决。
I'm trying to make the text from a div fade from black to white. Simple, yeah?
我正在尝试使 div 中的文本从黑色淡化为白色。很简单吧?
The following code works. It will change the color to white, however, the setTimeout time of 500ms is being ignored.
以下代码有效。它会将颜色更改为白色,但是会忽略 500 毫秒的 setTimeout 时间。
If you use Chrome and look at the JS console, you'll easily see that the doFade() method is being called almost instantaneously, not every 500 milliseconds.
如果您使用 Chrome 并查看 JS 控制台,您会很容易看到 doFade() 方法几乎是立即被调用的,而不是每 500 毫秒一次。
Can anyone explain this?
谁能解释一下?
var started = false;
var newColor;
var div;
var hex = 0;
function fadestart(){
if (typeof fadestart.storedColor == 'undefined') {
div = document.getElementById('test');
fadestart.storedColor = div.style.color;
}
if(!started){
console.log('fadestart');
newColor = fadestart.storedColor;
started = true;
setTimeout(doFade(), 500);
}
}
function fadestop(){
console.log('fadestop');
div.style.color = fadestart.storedColor;
started = false;
hex = 0;
}
function doFade(){
if(hex<=238){
console.log(hex);
hex+=17;
div.style.color="rgb("+hex+","+hex+","+hex+")";
setTimeout(doFade(), 500);
}
}
回答by KeatsKelleher
You need to get rid of the parentheses on doFade()
.
您需要去掉 上的括号doFade()
。
The parentheses invoke the function instantly.
括号立即调用该函数。
Just use this in stead: doFade
只需使用它: doFade
回答by deceze
setTimeout(doFade(), 500);
This line says "execute doFade()
, then pass whatever value it returns to setTimeout
, which will execute this return value after 500 milliseconds." I.e., you're calling doFade()
right there on the spot.
这一行表示“执行doFade()
,然后传递它返回的任何值setTimeout
,这将在 500 毫秒后执行此返回值。” 也就是说,你就doFade()
在现场打电话。
Skip the parentheses to passthe function to setTimeout
:
跳过括号将函数传递给setTimeout
:
setTimeout(doFade, 500);
回答by PeterWong
I think you should use setTimeout(doFade, 500);
or setTimeout("doFade()", 500);
我认为你应该使用setTimeout(doFade, 500);
或setTimeout("doFade()", 500);