Javascript递归超时调用 [英] Javascript recursive timeout call

查看:83
本文介绍了Javascript递归超时调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我尝试编写一个动态的onmouseout事件,当鼠标离开div时,它会慢慢改变不透明度。
出于某种原因,递归和超时似乎不是工作属性,并且不透明度的改变立即完成。



问题: 是否有任何理由使得 setTimeout()不适用于递归?有没有更好的方法来解决这个问题?

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


解决方案

将您的setTimeout调用更改为

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

所以它会在1s后执行,而不是立即执行

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

解决方案

Change your setTimeout call to

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

So it will execute after 1s, and not immediately

这篇关于Javascript递归超时调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆