setInterval小問題

先看下面代碼:html

1  for (var i = 0; i < 3; i++) {
2         setTimeout(function () {
3             console.log(i)
4         }, 1000);
5     }

運行效果是jquery

  

輸出了三次3,而要想輸出1,2,3,可改進代碼爲:閉包

1 for (var i=0;i<3;i++){
2         (function (i) {
3             setTimeout(function () {
4                 console.log(i);
5             },1000);
6         })(i);
7     }

效果:函數

簡要說一下鄙人拙見:this

  第一個代碼出現三次,3,的緣由是,for循環時間遠小於1000毫秒,因此for循環完了,計時器才運行的,獲取的就是三次3.spa

  第二個代碼:添了個閉包函數,當i每次累加的時候先執行下計時器,當等於一的時候執行計時器輸出1,同理出現2,3code

 

還有就是不要在計時器嵌套for循環htm

因此還有一下代碼:blog

1  var i = 0;
2     var id = setInterval(function () {
3         i++;
4         console.log(i);
5         if (i >= 12) {
6             clearInterval(id);
7         }
8     }, 100);

一個簡單例子,我的感受挺實用的。又不用嵌套for循環。。ip

 

 補充2016-09-30 11:07:19

經過jQuery each()方法實現

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>each</title>
 6     <script src="../base/jquery-3.1.0.js"></script>
 7     <style>
 8         * {
 9             margin: 0;
10             padding: 0;
11             list-style: none;
12         }
13 
14         .blueBg {
15             background: blue;
16         }
17 
18         .whiteBg {
19             background: white;
20         }
21     </style>
22 </head>
23 <body>
24 <ul>
25     <li>內容一</li>
26     <li>內容二</li>
27     <li>內容三</li>
28 </ul>
29 </body>
30 <script>
31     $(function () {
32         var timer = null;
33         $("ul li").each(function (i) {
34             $(this).hover(function () {
35                 var curLi = $(this);
36                 timer = setTimeout(function () {
37                     curLi.removeClass("whiteBg").addClass("blueBg");
38                     console.log(i);
39                 });
40             }, function () {
41                 clearTimeout(timer);
42                 $(this).removeClass("blueBg").addClass("whiteBg");
43             })
44         })
45     })
46 </script>
47 </html>
相關文章
相關標籤/搜索