定时器(深入)

复制代码
 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 @   YBYZ  阅读(48)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
点击右上角即可分享
微信分享提示