Javascript recursive timeout call

左心房为你撑大大i 提交于 2020-01-03 21:18:09

问题


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


来源:https://stackoverflow.com/questions/16887061/javascript-recursive-timeout-call

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!