对设置超时感到困惑

时间:2013-05-21 04:04:45

标签: javascript

我真的很困惑这些工作如何...超时似乎没有继续运行它只调用begin_anim然后就是它......

所以我希望有人能看到我出错的地方并解释我是如何实现的?

这是我的代码:

//test data:
//type = 'up';
//div = document.getElementById('theid');
//marginL = -400;

function timeout_begin(type,div,marginL){   
    setTimeout(begin_anim(type,div,marginL),1000);
}

function begin_anim(type,div,marginL){
    if(type == 'up'){
        if(marginL >= '-200'){ 
                if(marginL > '-200'){ 
                    div.style.marginLeft = '-200px';
                }
            return false;
        }
    marginL += 2;
    div.style.marginLeft = marginL+'px';


    }
    return false;
}

希望你能帮忙!

4 个答案:

答案 0 :(得分:4)

您正在寻找setInterval

此外,最好传递一个实际的函数,你可以保持对循环的引用,这样你就可以在以后停止运行:

var animationLoop = setInterval(function () {
       begin_anim(type, div, marginL);
    }, 1000);

clearInterval(animationLoop); // This would then stop the loop.

答案 1 :(得分:1)

setTimeout应该只调用一次函数。

如果要重复调用该方法,请使用setInterval(function(){}, 1000/*duration*/)

答案 2 :(得分:1)

首先,您需要setInterval,而不是setTimeout

其次,您将引用传递给函数,而不是调用传递给函数。类似的东西:

function timeout_begin(type,div,marginL)
{   
  setTimeout(
    function() { 
      begin_anim(type,div,marginL);
    }, 
    1000
  );
}

答案 3 :(得分:0)

setTimeout只能在给定的超时后执行一次该函数。请参阅此处的文档:http://www.w3schools.com/jsref/met_win_settimeout.asp

你可能正在寻找setInterval(http://www.w3schools.com/jsref/met_win_setinterval.asp),它以你设置的间隔执行代码,直到调用clearInterval。