Javascript recursive timeout call

2019-07-07 06:18发布

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
    }
}

4条回答
混吃等死
2楼-- · 2019-07-07 06:44

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
    }

}

查看更多
ら.Afraid
3楼-- · 2019-07-07 06:46

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楼-- · 2019-07-07 06:50

Change your setTimeout call to

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

So it will execute after 1s, and not immediately

查看更多
Fickle 薄情
5楼-- · 2019-07-07 06:55

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

查看更多
登录 后发表回答