倒计时例子

效果图:

代码:

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>setTimeout倒计时</title>
 6     <script>
 7     var i = 5;
 8     var t;
 9     function startCount(){ 
10         if (i<0) {
11            stop();
12        }else{
13          document.getElementById("text").value = i;
14          t=setTimeout("startCount()",1000);
15          i =i-1; 
16        }    
17     }
18 
19     function stop(){
20            clearTimeout(t);
21            alert("游戏结束");    
22     }
23     
24     </script>
25 </head>
26 <body>
27 <input type="text" id="text">
28 <input type="button" id="start" onclick="startCount()" value="开始">    
29 </body>
30 </html>

注意:if判断语句要放在前面,赋值语句要放在自减前面,因为执行顺序问题,所以代码顺序不能乱,乱了就各种问题,得不到想要的效果。

 

posted @ 2017-08-21 11:41  脑袋空空空想家  阅读(290)  评论(0编辑  收藏  举报