setTimeout ignores timeout? (Fires immediately) [duplicate]
This is my first real dive into JavaScript. Sure I've used it before, but I've never really written anything from scratch.
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?
The following code works. It will change the color to white, however, the setTimeout time of 500ms is being ignored.
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.
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);
}
}
You need to get rid of the parentheses on doFade()
.
The parentheses invoke the function instantly.
Just use this in stead: doFade
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.
Skip the parentheses to pass the function to setTimeout
:
setTimeout(doFade, 500);
I think you should use setTimeout(doFade, 500);
or setTimeout("doFade()", 500);
精彩评论