setTimeout()与setInterval()之间的区别

使用setTimeout(),clearTimeout()延时执行函数、清除函数的延迟执行。必须放到函数里面。

例如://setTimeout
<h1 id="output" ></h1>
<script type="text/javascript">
 var c=10;
 (function (){
   if(c){
   setTimeout(arguments.callee,1000)
  } document.getElementById("output").innerHTML=c;
 c--;
 })()
</script>

setInterval(),clearInterval()定时执行函数,setInterval() 方法会不停地调用函数,直到 clearInterval() 被调用或窗口被关闭。由 setInterval() 返回的 ID 值可用作 clearInterval() 方法的参数.不需要放到函数里。

//setInterval()
<h1 id="output" ></h1>
<script type="text/javascript">
 var c=10;
 document.getElementById("output").innerHTML=c;
 var timer =setInterval(function(){
  document.getElementById("output").innerHTML=--c;
 if (c==-5)clearInterval(timer)
 },1000)
</script>

原文地址:https://www.cnblogs.com/yansen/p/2470079.html