setInterval 和 setTimeout

这两个函数都是定时器,都是window对象的函数,但是还是有很多区别的。

1.根本区别

setTimeout("function", time),function为函数名或代码,time单位毫秒,指在载入后延迟指定时间去执行函数一次

setInteval("function", interval),指在载入后每隔指定时间执行一次

2.setTimeout循环调用

setTimeout 可以通过写在函数中,然后function指定为这个外部函数,来达到循环延迟执行的效果,类似setInterval。

function movePic(nowid, nextid, direction){
    now = document.getElementById(nowid+"");            
    next = document.getElementById(nextid+"");
    //为防止频繁快速调用(如鼠标很快的移动)造成的拉扯,所以每次都将积累在setTimeout队列中的事件清除;
    if(pic.movement){
        clearTimeout(pic.movement);
    }                
    var nowleft = parseInt(now.style.left);
    var nextleft = parseInt(next.style.left);
    var dist = 0;
    if(direction){
        var nowtoleft = -800;
    }
    else{
        var nowtoleft = 800;
    }
    if(nowleft == nowtoleft){return true;                 //相等时返回函数,停止循环调用
    }
    else if(nowleft > nowtoleft){
        dist = Math.ceil((nowleft - nowtoleft)/20);//变速运动
        nowleft -= dist;
        nextleft -= dist;
    }
    else{
        dist = Math.ceil((nowtoleft - nowleft)/20);//变速运动
        nowleft += dist;
        nextleft += dist;
    }
    now.style.left = nowleft+'px';
    next.style.left = nextleft+'px';
    var repeat = "movePic('"+nowid+"','"+nextid+"',"+direction+")";    
    //movement设置成全局变量会造成上面开始那里“没有设置就清除”的错误;若设置成局部变量,
    //则局部变量在clearTimeout函数的上下文里不存在,使其不能正常工作;
    //所以设置成一个变量的属性;        
    pic.movement = this.setTimeout(repeat, 1);
}

这有几个特点:

可以通过逻辑来指定何时停止循环,通过return方式;

setInterval每隔固定时间就调用,不管前面的有没有完成,而这种setTimeout的方式可以保证是在前面函数执行完毕后再计时延迟调用的。

3.clearTimeout 和 clearInterval

clearInterval 可以使定时循环停止,而clearTimeout一般是如上面注释那样,清除积累队列,避免拉扯。

为了可以清除,要把定时函数赋给一个变量,而这个变量也是有所不同的:

setInterval可以直接赋给一个全局变量,不会有问题;

在通过嵌套循环的方式用setTimeout时就要注意了,这个变量设置成全局变量会造成上面开始那里“没有设置就清除”的错误;若设置成局部变量,则局部变量在clearTimeout函数的上下文里不存在,使其不能正常工作;所以,一般将它作为被操作对象的属性,最开始清除时,属性存在才清除。

原文地址:https://www.cnblogs.com/babywhale/p/4612823.html