定时器(深入)

 1 // 定时器
 2 // js提供了定时执行js代码的功能,叫定时器。主要由两个内置的定时器方法实现。
 3 
 4 
 5 
 6 
 7 // 一. setTimeout(function(){},delay);
 8 // 1. 该函数指定某个方法在,delay毫秒之后执行,只执行一次。返回值是该定时器在程序内部的索引值.
 9 var index=setTimeout(function () { 
10 document.write('hello')
11 }, 2000)
12 console.log(index);
13 // 2. clearTimeout(index);//根据定时器的索引清除定时器,定时器不会运行。
14 clearTimeout(index)
15 
16 
17 
18 
19 // 3. 实现每隔一段时间执行函数
20 // 3.1 输出5次hello就停止。
21 /* 
22 var num = 1;
23 function time() {
24     setTimeout(function () { 
25         console.log('hello');
26         num++;
27         if (num < 6) {
28             time()
29         }
30      
31     },2000)
32 }
33 time()
34  */
35 
36 
37 
38 
39 
40 
41 // 二、setInterval(function,delay),每隔delay毫秒执行一次函数,会一直执行。返回值是该定时器的索引值
42 /* 
43 var index2= setInterval(function () {
44     console.log(12);
45 }, 2000)
46 
47  */
48 //2.停止定时器
49 // clearInterval(index2)
50 
51 // 3. 输出5次hello就停止。
52 
53 /* 
54 var num = 1;
55 var index3= setInterval(function () {
56     console.log('hello');
57     num++
58     if (num > 5) {
59         clearInterval(index3)
60     }
61 }, 2000)
62 
63  */
64 
65 // 三、 如果计时器用变量代替函数,变量不要添加()
66 /* 
67 
68 var handle = function () {
69     console.log(34)
70 }
71 setInterval(handle,2000)
72 
73  */
74 var handle = function (a,b) {
75     console.log(a+b);
76 }
77 setTimeout(handle,2000,1,2)

 

posted @ 2022-08-19 22:56  YBYZ  阅读(64)  评论(0)    收藏  举报