这两个函数都是定时器,都是window对象的函数,可是仍是有不少区别的。函数
1.根本区别this
setTimeout("function", time),function为函数名或代码,time单位毫秒,指在载入后延迟指定时间去执行函数一次。spa
setInteval("function", interval),指在载入后每隔指定时间执行一次。code
2.setTimeout循环调用对象
setTimeout 能够经过写在函数中,而后function指定为这个外部函数,来达到循环延迟执行的效果,相似setInterval。blog
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的方式能够保证是在前面函数执行完毕后再计时延迟调用的。get
3.clearTimeout 和 clearIntervalio
clearInterval 能够使定时循环中止,而clearTimeout通常是如上面注释那样,清除积累队列,避免拉扯。
为了能够清除,要把定时函数赋给一个变量,而这个变量也是有所不一样的:
setInterval能够直接赋给一个全局变量,不会有问题;
在经过嵌套循环的方式用setTimeout时就要注意了,这个变量设置成全局变量会形成上面开始那里“没有设置就清除”的错误;若设置成局部变量,则局部变量在clearTimeout函数的上下文里不存在,使其不能正常工做;因此,通常将它做为被操做对象的属性,最开始清除时,属性存在才清除。