快速掌握Node.js中setTimeout及setInterval的使用方法总结计划.docx

快速掌握Node.js中setTimeout及setInterval的使用方法总结计划.docx

  1. 1、本文档共2页,可阅读全部内容。
  2. 2、原创力文档(book118)网站文档一经付费(服务费),不意味着购买了该文档的版权,仅供个人/单位学习、研究之用,不得用于商业用途,未经授权,严禁复制、发行、汇编、翻译或者网络传播等,侵权必究。
  3. 3、本站所有内容均由合作方或网友上传,本站不对文档的完整性、权威性及其观点立场正确性做任何保证或承诺!文档内容仅供研究参考,付费前请自行鉴别。如您付费,意味着您自己接受本站规则且自行承担风险,本站不退款、不进行额外附加服务;查看《如何避免下载的几个坑》。如果您已付费下载过本站文档,您可以点击 这里二次下载
  4. 4、如文档侵犯商业秘密、侵犯著作权、侵犯人身权等,请点击“版权申诉”(推荐),也可以打举报电话:400-050-0827(电话支持时间:9:00-18:30)。
查看更多
这篇文章主要为大家介绍了快速掌握 Node.js 中 setTimeout 和 setInterval 的使用方法,感兴趣的小伙伴们可以参考一下 Node.js 和 js 一样也有计时器 ,超时计时器、间隔计时器、及时计时器,它们以及 process.nextTick(callback) 函数来实现事件调度。 今天先学下 setTimeout 和 setInterval 的使用。 一、 setTimeout 超时计时器 (和 GCD 中的 after 类似 ) 在 node.js 中可以使用 node.js 内置的 setTimeout(callback,delayMillSeconds,[args]) 方法。当调用 setTime()时回调函数会在 delayMillSeconds 后 执行 .setTime() 会返回一个定时器对象 ID ,可以在 delayMillSeconds 到期前将 ID 传给 clearTimeout(timeoutId) 来取消。 function myfunc(){ nbsp;console.log(myfunc); }; var mytimeout=setTimeout(myfunc,1000); clearTimeout(mytimeout); ---------------------------------------------------------- C:\Program Files (x86)\JetBrains\WebStorm 11.0.3\bin\runnerw.exe F:\nodejs\node.exe timer.js Process finished with exit code 0 如果将 clearTimeout(mytimeout); 这行注释之后可以看到是会执行 myfunc() 。 C:\Program Files (x86)\JetBrains\WebStorm 11.0.3\bin\runnerw.exe F:\nodejs\node.exe timer.js myfunc Process finished with exit code 0 二、 setInterval 间隔计时器 (和 GCD 中的 dispatch_source_t 或 NSTimer 类似 ) 间隔计时器用来按定期的时间间隔来执行工作 . 和  setTimeout  类似  ,node.js  中内置 setInterval(callback,delayMilliSecond,[args])  来创建并返回定时器对象  Id,通过  clearInterval() 来取消。 /** nbsp;* Created by Administrator on 2016/3/11. nbsp;*/ function myfunc(Interval){ nbsp;console.log(myfunc +Interval); } var myInterval=setInterval(myfunc,1000,Interval); function stopInterval(){ nbsp;clearTimeout(myInterval); nbsp;//myInterval.unref(); } setTimeout(stopInterval,5000); 上面代码是创建 setInterval 的回调函数 myfunc ,参数为 Interval , setInterval 每隔 1s 执行一次, setTimeout 是在 5 秒之后执行,它的回调函数让间隔计时器取消。 C:\Program Files (x86)\JetBrains\WebStorm 11.0.3\bin\runnerw.exe F:\nodejs\node.exe Interval.js myfunc Interval myfunc Interval myfunc Interval myfunc Interval Process finished with exit code 0 三、从事件循环中取消定时器引用 当事件队列中仅存在定时器回调函数时,如果不希望再执行它们,可以使用 和 setTimeout 返回对象的 unref() 函数来通知事件循环不要继续。 当 unref() 和 setTimeout 结合使用, 要用独立计时器来唤醒事件循环, 会产生影响,应尽量少用。 四、 setTimeout 和 setInterval 执行时间是不精确的 它们是间隔一定时间将回调添加到事件队列中 ,执行也不是太精确  setInterval 大量使用对性能也 function si

文档评论(0)

136****9452 + 关注
实名认证
内容提供者

该用户很懒,什么也没介绍

1亿VIP精品文档

相关文档