- 1、本文档共2页,可阅读全部内容。
- 2、原创力文档(book118)网站文档一经付费(服务费),不意味着购买了该文档的版权,仅供个人/单位学习、研究之用,不得用于商业用途,未经授权,严禁复制、发行、汇编、翻译或者网络传播等,侵权必究。
- 3、本站所有内容均由合作方或网友上传,本站不对文档的完整性、权威性及其观点立场正确性做任何保证或承诺!文档内容仅供研究参考,付费前请自行鉴别。如您付费,意味着您自己接受本站规则且自行承担风险,本站不退款、不进行额外附加服务;查看《如何避免下载的几个坑》。如果您已付费下载过本站文档,您可以点击 这里二次下载。
- 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
您可能关注的文档
- 差生辅导计划差生辅导学习记录差生转化计划.docx
- 师范生教育实习总结计划10篇范文版本.docx
- 希腊神话故事两则学习教案沪教版本好学习教案.docx
- 帮助别人的感觉真好的作文500字数高质量版本.docx
- 常规心电图及动态心电图诊断冠心病心律失常的比较研究.docx
- 干式变压器温控系统软件使用学习手册.docx
- 平凡中的伟大的作文600字数版本.docx
- 平淡中也有诗的作文600字数版本.docx
- 年产11万吨顺丁橡胶生产工艺设计说明书范文.docx
- 年夜饭的作文1000字数版本.docx
- 四川省德阳市罗江中学2025届高三考前热身化学试卷含解析.doc
- 山东省枣庄现代实验学校2025届高三下学期第五次调研考试化学试题含解析.doc
- 吉林省长春市十一高中等九校教育联盟2025届高三一诊考试生物试卷含解析.doc
- 2025届江苏省盐城市伍佑中学高考仿真模拟化学试卷含解析.doc
- 2025届广西贺州中学高考冲刺押题(最后一卷)生物试卷含解析.doc
- 安徽省池州市贵池区2025届高三第一次模拟考试生物试卷含解析.doc
- 宁夏银川一中2025届高三(最后冲刺)化学试卷含解析.doc
- 广东省广州市增城区四校联考2025届高考压轴卷化学试卷含解析.doc
- 2025届邯郸市第一中学高考生物必刷试卷含解析.doc
- 2025届安徽省安庆市石化第一中学高考仿真卷化学试卷含解析.doc
文档评论(0)