JS中setTimeout()的用法详解

原文来自:http://blog.csdn.net/suwu150/article/details/54577133

 

setTimeout( ) 是属于 window 的 method, 但我们都是略去 window 这顶层容器名称, 这是用来设定一个时间, 时间到了, 就会执行一个指定的 method

 请先看以下一个简单, 这是没有实际用途的例子, 只是用来示范 setTimeout( ) 的语法。

1、setTimeout( ) 语法例子

  1. <html>  
  2. <body text=red>  
  3. <h1> <font color=blue> 示范网页 </font> </h1> <p> </br>  
  4. <p> 请等三秒钟!  
  5. <script>  
  6. setTimeout("alert('对不起, 三秒钟已到')", 3000 )  
  7. </script>  
  8. </body> </html>  
<html>
<body text=red>
<h1> <font color=blue> 示范网页 </font> </h1> <p> </br>
<p> 请等三秒钟!
<script>
setTimeout("alert('对不起, 三秒钟已到')", 3000 )
</script>
</body> </html>

2. 留意网页开启后三秒, 就会出现一个 alert 对话盒。

  setTimeout( )是设定一个指定等候时间 (单位是千分之一秒, millisecond), 时间到了, 浏览器就会执行一个指定的 method 或 function, 有以下语法:

  这次例子是设定等待 3 秒 (3000 milliseconds), 浏览器就会执行 alert( ) 这一个method,注意这个函数可以由我们自己重新书写。下面就来看一看调用function的方式 

  1. <html>  
  2.  <head></head>  
  3.  <body text="red">   
  4.   <h1><font color="blue"> 示范网页 </font></h1>   
  5.   <script>  
  6. // setTimeout("alert('出窗')",3000 );  
  7. setTimeout("changeState()",3000 );  
  8. function changeState(){  
  9.   // alert("弹出");  
  10.   let content=document.getElementById('content');  
  11.   content.innerHTML="<div>这是三秒钟之后</div>";  
  12. }  
  13. </script>   
  14.   <p id="content"> 请等三秒钟!</p>    
  15.  </body>  
  16. </html>  
<html>
 <head></head>
 <body text="red"> 
  <h1><font color="blue"> 示范网页 </font></h1> 
  <script>
// setTimeout("alert('出窗')",3000 );
setTimeout("changeState()",3000 );
function changeState(){
  // alert("弹出");
  let content=document.getElementById('content');
  content.innerHTML="<div>这是三秒钟之后</div>";
}
</script> 
  <p id="content"> 请等三秒钟!</p>  
 </body>
</html>

以上这段代码是实现一个在3秒钟之后进行更换文本的内容,在更换内容的时候调用了方法changeState()方法

 

3、有了以上基础,我们可以实现一个自动运行的按照时间递加的计数器,如下面所示代码:

 

  1. <html>  
  2. <body text=red>  
  3. <h1><font color=blue> 示范网页 </font></h1>  
  4. <script>  
  5.   var x=0;  
  6.   
  7.   function changeState(){  
  8.         x=x+1;  
  9.         //注意这里的调用方式,使用引号包围  
  10.         setTimeout("changeState()",1000 );  
  11.         let content=document.getElementById('content');  
  12.          content.innerHTML=x;  
  13.          console.log(x);  
  14.       }  
  15. </script>  
  16. <button onclick="changeState()">开始计时</button>  
  17. <p>已运行时间</p>  
  18. <p id="content"></p>  
  19. </body>  
  20. </html>  
<html>
<body text=red>
<h1><font color=blue> 示范网页 </font></h1>
<script>
  var x=0;

  function changeState(){
        x=x+1;
        //注意这里的调用方式,使用引号包围
        setTimeout("changeState()",1000 );
        let content=document.getElementById('content');
         content.innerHTML=x;
         console.log(x);
      }
</script>
<button onclick="changeState()">开始计时</button>
<p>已运行时间</p>
<p id="content"></p>
</body>
</html>

在上面代码中,当点击按钮启动changeState( )后, 就会启动 setTimeout( ), 这个 method 在一秒后又启动 changeState( ), changeState( )启动后又启动 setTimeout( ) , 所以得出的结果是 changeState( )每秒执行一次,继而实现数值的递增。

 

虽然实现了数值的递增,但是当我们连续点击按钮时,你会发现,数值的增加不是按照1秒增加的(小于1秒),下面,我们进行一些限制条件,比如限制x<60,然后重新开始,在其他位进1,也就是实现钟表计时功能,如下面代码:

 

[javascript] view plain copy print?
  1. <html>  
  2. <body text=red>  
  3. <h1><font color=blue> 示范网页 </font></h1>  
  4. <script>  
  5.   var x=00;  
  6.   var y=00;  
  7.   var z=00;  
  8.   
  9.   function changeState(){  
  10.     if(x<=59&&x>=0 && y<=59 && y>=0 && z<=59 && z>=0){  
  11.       //注意这里的调用方式,使用引号包围  
  12.       let content=document.getElementById('content');  
  13.        content.innerHTML=z+":"+y+":"+x;  
  14.        console.log(x);  
  15.         x=x+1;  
  16.     }else if(y<=59 && y>=0 && z<=59 && z>=0){  
  17.       y=y+1;  
  18.       x=0;  
  19.     }  
  20.     else if (z<=59 && z>=0) {  
  21.       z=z+1;  
  22.       y=0;  
  23.       x=0;  
  24.     }  
  25.     setTimeout("changeState()",1000 );  
  26.   }  
  27. </script>  
  28. <button onclick="changeState()">开始计时</button>  
  29. <p>已运行时间</p>  
  30. <p id="content"></p>  
  31. </body>  
  32. </html>  
<html>
<body text=red>
<h1><font color=blue> 示范网页 </font></h1>
<script>
  var x=00;
  var y=00;
  var z=00;

  function changeState(){
    if(x<=59&&x>=0 && y<=59 && y>=0 && z<=59 && z>=0){
      //注意这里的调用方式,使用引号包围
      let content=document.getElementById('content');
       content.innerHTML=z+":"+y+":"+x;
       console.log(x);
        x=x+1;
    }else if(y<=59 && y>=0 && z<=59 && z>=0){
      y=y+1;
      x=0;
    }
    else if (z<=59 && z>=0) {
      z=z+1;
      y=0;
      x=0;
    }
    setTimeout("changeState()",1000 );
  }
</script>
<button onclick="changeState()">开始计时</button>
<p>已运行时间</p>
<p id="content"></p>
</body>
</html>

实现效果如下所示:

 

3、既然有开始计时,那么想当然就要有停止计时,那么就需要知道这个函数------clearTimeout( )

  setTimeout( ) 来使到浏览器不断执行一个 function, 当一个 setTimeout( ) 开始了循环的工作, 我们要使它停下来, 可使用 clearTimeout( ) 这 method。   clearTimout( ) 有以下语法: clearTimeout(timeoutID)   要使用 clearTimeout( ), 我们设定 setTimeout( ) 时, 要给予这 setTimout( ) 一个名称, 这名称就是 timeoutID , 我们叫停时, 就是用这 timeoutID来叫停, 这是一个自定义名称,。 如下: timeoutID  ↓ meter1 =setTimeout("count1()", 1000) meter2 =setTimeout("count2()", 1000)   使用这 meter1 及 meter2 这些 timeoutID 名称, 在设定 clearTimeout( ) 时, 就可指定对哪一个 setTimeout( ) 有效, 不会扰及另一个 setTimeout( ) 的操作。

如下所示,停止的语句(注意:count1(),count2()分别是计时开始的方法,而meter1,meter2分别是setTimeout的定义)

  1. <html>  
  2.  <head>   
  3.   <script>  
  4. x = 0  
  5. y = 0  
  6.   
  7. function count1( )  
  8. { x = x+ 1  
  9.   document.display1.box1.value= x  
  10.   meter1=setTimeout("count1()", 1000)  
  11. }  
  12.   
  13. function count2( )  
  14. { y = y+ 1  
  15.   document.display2.box2.value= y  
  16.   meter2=setTimeout("count2()", 1000)  
  17. }  
  18. </script>   
  19.  </head>   
  20.  <body bgcolor="lightcyantext=red">   
  21.   <p<br /> </p>  
  22.   <form name="display1">   
  23.    <input type="text" name="box1" value="0" size="4" />   
  24.    <input type="button" value="停止计时" onclick="clearTimeout(meter1)" />   
  25.    <input type="button" value="继续计时" onclick="count1() " />   
  26.   </form>   
  27.   <p</p>  
  28.   <form name="display2">   
  29.    <input type="text" name="box2" value="0" size="4" />   
  30.    <input type="button" value="停止计时" onclick="clearTimeout(meter2) " />   
  31.    <input type="button" value="继续计时" onclick="count2( ) " />   
  32.   </form>   
  33.   <script>  
  34. count1( )  
  35. count2( )  
  36. </script>    
  37.  </body>  
  38. </html>  
<html>
 <head> 
  <script>
x = 0
y = 0

function count1( )
{ x = x+ 1
  document.display1.box1.value= x
  meter1=setTimeout("count1()", 1000)
}

function count2( )
{ y = y+ 1
  document.display2.box2.value= y
  meter2=setTimeout("count2()", 1000)
}
</script> 
 </head> 
 <body bgcolor="lightcyantext=red"> 
  <p> <br /> </p>
  <form name="display1"> 
   <input type="text" name="box1" value="0" size="4" /> 
   <input type="button" value="停止计时" onclick="clearTimeout(meter1)" /> 
   <input type="button" value="继续计时" onclick="count1() " /> 
  </form> 
  <p> </p>
  <form name="display2"> 
   <input type="text" name="box2" value="0" size="4" /> 
   <input type="button" value="停止计时" onclick="clearTimeout(meter2) " /> 
   <input type="button" value="继续计时" onclick="count2( ) " /> 
  </form> 
  <script>
count1( )
count2( )
</script>  
 </body>
</html>

4、设置点击一次标志--- Set flag   前个练习说到我们用一个按钮来启动一个 function, 每按一下就会启动这 function 一次, 请看以下例子。  在这例子有以下设定: 1. 程序开启时 flag=0。 2. 当 counter( ) 执行时会顺便将 flag 变为 1。 3. 在 [继续计时] 这按钮的反应中, 会先检查 flag 是 0 或是 1, 若是 0 就会产生作用, 若是 1 就没有反应。 4. 使用这 flag 的方式, count( ) 这 function 开启后, [继续计时] 这按钮就没有作用。   这处的 flag 是一个变数, 可任意取名, 我们用 flag来称呼这变数的原因, 是因为这变数好处一支旗, 将旗竖起 (flag is on), 就会产生一个作用, 将旗放下 (flag is off), 就产生另一个作用。 练习---只可开启一次的 function   这练习是将上个练习加多一个 flag, 使到每次只能有一个 count( ) 这 function 在进行。 以下内容:

  1. <html>  
  2.  <head>   
  3.   <script>  
  4. x = 0  
  5. flag = 0  
  6. function count( )  
  7. { x = x+ 1  
  8.   document.display.box.value= x  
  9.   timeoutID=setTimeout("count()", 1000)  
  10.   flag = 1  
  11. }  
  12.   
  13. function restart( )  
  14. { if (flag==0)  
  15.    { count( ) }  
  16. }  
  17. </script>   
  18.  </head>   
  19.  <body bgcolor="lightcyantext=red">   
  20.   <p> <br /> </p>  
  21.   <form name="display">   
  22.    <input type="text" name="box" value="0" size="4" />   
  23.    <input type="button" value="停止计时"   onclick="clearTimeout(timeoutID);flag=0" />   
  24.    <input type="button" value="继续计时" onclick="restart() " />   
  25.   </form>   
  26.   <p> <script>  
  27. count( )  
  28. </script> </p>  
  29.   <form>   
  30.    <input type="button" value="Show flag" onclick="alert('The flag now is '+ flag)" />   
  31.   </form>    
  32.  </body>  
  33. </html>  
<html>
 <head> 
  <script>
x = 0
flag = 0
function count( )
{ x = x+ 1
  document.display.box.value= x
  timeoutID=setTimeout("count()", 1000)
  flag = 1
}

function restart( )
{ if (flag==0)
   { count( ) }
}
</script> 
 </head> 
 <body bgcolor="lightcyantext=red"> 
  <p> <br /> </p>
  <form name="display"> 
   <input type="text" name="box" value="0" size="4" /> 
   <input type="button" value="停止计时"   onclick="clearTimeout(timeoutID);flag=0" /> 
   <input type="button" value="继续计时" onclick="restart() " /> 
  </form> 
  <p> <script>
count( )
</script> </p>
  <form> 
   <input type="button" value="Show flag" onclick="alert('The flag now is '+ flag)" /> 
  </form>  
 </body>
</html>

效果说明:

 

1. 在网页中, 你应见到三个按钮及文字框中的数字跳动。 2. 请你按 [Show flag]这按钮, 应见到一个话对盒显示 flag 是 1。 3. 请你按 [停止计时]这按钮, 数字停止跳动, 请你按 [Show flag] 这按钮, 应见到话对盒显示 flag 是 0。 4. 请你按多次 [继续计时]这按钮, 你应见到数字不会加快, 请你按 [Show flag]这按钮, 应见到话对盒显示 flag 变回 1。

代码解析:

1. 这网页第 5行有这一句: flag=0 , 这是设定 flag 这变量及将初始值定为 0, 你也可将初始值定为 1, 随后有关的 0 和 1 对调。 2. count( ) 这个 function方法中最后一句是 flag=1 , 所以启动 count( ) 后, flag的状态就会变为 1。 3. [继续计时] 的按钮是用来启动 restart( ), 这 function 有以下设定: function restart( ) { if (flag==0)    { count( ) } }   这里的 if statement 检查 flag是否等于 0, 若是 0 就启动 count(), 若是 1 (即不是 0) 就没有反应,使用这方法, 若 count( )已在执行中, [继续计时] 这按钮不会有作用。   这处的 flag=1设定, 实际设为 1 或 2 或 3 等数值都是一样的,只要不是 0 就可以了, 所以这两个相对的标志,看似是 "0" 和 "1", 实际是"0" 和 "non-zero" (非-0)。 4. [停止计时] 的按钮有以下设定: onClick="clearTimeout(timeoutID);flag=0"   这是停止 setTimeout( ) 的操作时,同时将 flag 传回 0, 这使到restart( ) 这function 可以重新启动 count()。

 

注意:下面方法是定时作用,能够按照一定的时间执行相同的操作setInterval

 

[javascript] view plain copy print?
  1. let i =0;  
  2. setInterval(() => {  
  3.   console.log(i++);  
  4. },1500);//1000为1秒钟  
let i =0;
setInterval(() => {
  console.log(i++);
},1500);//1000为1秒钟

在上面代码中,每隔1.5秒就会有一次打印,对于这个方法,同样能够实现上面操作中的始终功能,并且代码更加简单.


  应该值得注意的是: setTimeout 也有个小细节,第二个参数设置为 0 也许会有人认为这样就不是异步了,其实还是异步。这是因为 HTML5 标准规定这个
函数第二个参数不得小于 4 毫秒,不足会自动增加。
posted @ 2018-02-08 10:46  抹茶MM  阅读(945)  评论(0)    收藏  举报