Javascript recursive timeout call

2019-07-07 06:19发布

问题:

This is my attempt at writing a dynamic onmouseout event that slowly changes the opacity when the mouse leaves the div. For some reason the recursion and timeout seem to be no working property and the change in opacity is done immediately.

The question: Is there any reasons that setTimeout() does not work with recursion? Is there a better way to approach this problem?

function hide(id)
{
    if (gOpacity > .4) 
    {
        gOpacity -= .1;
        document.getElementById(id).style.opacity = gOpacity;
        setTimeout(hide(id),1000)
    }
    else 
    {
        gOpacity = 1.0
    }
}

回答1:

Change your setTimeout call to

setTimeout(function() { hide(id); } ,1000)

So it will execute after 1s, and not immediately



回答2:

Have you tried this?

function hide(id)
{
    if (gOpacity > .4) 
    {
        gOpacity -= .1;
        document.getElementById(id).style.opacity = gOpacity;
        setTimeout(function() {
           hide(id);
        },1000)
    }
    else 
    {
        gOpacity = 1.0
    }

}



回答3:

i thinck that when you type :

 setTimeout(hide(id),1000);

what you really mean is :

  setTimeout(hide.bind(this,id),1000);

becasue in the first case, the function will be call instantly when setTimeout is call - it is an argument of setTimeout- .
In the second case, this will be a bound function. So yes this and id are evaluated, but the function is not called until the 1000 ms elapsed.

(this is just a faster to run / faster to type way of creating a function ).



回答4:

wrap all your code in recursive function by setTimeout

function hide(id)
{
    setTimeout(function() {
        if (gOpacity > .4) 
        {
            gOpacity -= .1;
            document.getElementById(id).style.opacity = gOpacity;   
            hide(id);
        }
        else 
        {
            gOpacity = 1.0
        }
    },1000)
}