开发者

setTimeout ignores timeout? (Fires immediately) [duplicate]

开发者 https://www.devze.com 2023-01-23 18:40 出处:网络
This question already has answers here: Why is my function call that should be scheduled by setTimeout executed immediately? [duplicate]
This question already has answers here: Why is my function call that should be scheduled by setTimeout executed immediately? [duplicate] (3 answers) 开发者_运维知识库 Why is the method executed immediately when I use setTimeout? (8 answers) Closed 8 years ago.

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);

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号