定时器(深入)
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)
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构