快速掌握Node.js中setTimeout和setInterval的使用方法
作者:bea
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(){
console.log("myfunc");
};
var mytimeout=setTimeout(myfunc,1000);
clearTimeout(mytimeout);
"C:Program Files (x86)JetBrainsWebStorm 11.0.3in unnerw.exe" F:
odejs
ode.exe timer.js
Process finished with exit code 0
如果将clearTimeout(mytimeout);这行注释之后可以看到是会执行myfunc()。
"C:Program Files (x86)JetBrainsWebStorm 11.0.3in unnerw.exe" F:
odejs
ode.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()来取消。
/**
* Created by Administrator on 2016/3/11.
*/
function myfunc(Interval){
console.log("myfunc "+Interval);
}
var myInterval=setInterval(myfunc,1000,"Interval");
function stopInterval(){
clearTimeout(myInterval);
//myInterval.unref();
}
setTimeout(stopInterval,5000);
上面代码是创建setInterval的回调函数myfunc,参数为Interval,setInterval每隔1s执行一次,setTimeout是在5秒之后执行,它的回调函数让间隔计时器取消。
"C:Program Files (x86)JetBrainsWebStorm 11.0.3in unnerw.exe" F:
odejs
ode.exe Interval.js
myfunc Interval
myfunc Interval
myfunc Interval
myfunc Interval
Process finished with exit code 0
三、从事件循环中取消定时器引用
当事件队列中仅存在定时器回调函数时,如果不希望再执行它们,可以使用setInterval和setTimeout返回对象的unref()函数来通知事件循环不要继续。
当unref()和setTimeout结合使用,要用独立计时器来唤醒事件循环,大量使用对性能也会产生影响,应尽量少用。
四、setTimeout和setInterval执行时间是不精确的
它们是间隔一定时间将回调添加到事件队列中,执行也不是太精确
function simpleTimeout(consoleTime)
{
console.timeEnd(consoleTime);
}
console.time("twoSecond");
setTimeout(simpleTimeout,2000,"twoSecond");
console.time("oneSecond");
setTimeout(simpleTimeout,1000,"oneSecond");
console.time("fiveSecond");
setTimeout(simpleTimeout,5000,"fiveSecond");
console.time("50MillSecond");
setTimeout(simpleTimeout,50,"50MillSecond");
以上代码多执行几次输出的结果也是不一样的。
"C:Program Files (x86)JetBrainsWebStorm 11.0.3in unnerw.exe" F:
odejs
ode.exe timer.js
50MillSecond: 51ms
oneSecond: 1000ms
twoSecond: 2002ms
fiveSecond: 5001ms
Process finished with exit code 0
以上就是本文的全部内容,希望对大家学习Node.js中setTimeout和setInterval的使用方法有所帮助。
猜你喜欢
您可能感兴趣的文章:
- javascript函数命名的三种方式及区别介绍
- javascript仿京东导航左侧分类导航下拉菜单效果
- JS中多种方式创建对象详解
- 基于jquery实现无限级树形菜单
- javascript的几种继承方法介绍
- 基于javascript实现文字无缝滚动效果
- ajax在兼容模式下失效的快速解决方法
- jquery仿QQ登录账号选择下拉框效果
- 详述JavaScript实现继承的几种方式(推荐)
- jQuery toggle 代替方法
- 一款简单的jQuery图片标注效果附源码下载
- 酷炫jQuery全屏3D焦点图动画效果
- 浅析C/C++,Java,PHP,JavaScript,Json数组、对象赋值时最后一个元素后面是否可以带逗号
- 使用struts2+Ajax+jquery验证用户名是否已被注册
- 使用getBoundingClientRect方法实现简洁的sticky组件的方法
- Node.js文件操作方法汇总
- 浅谈Sticky组件的改进实现
- 使用Sticky组件实现带sticky效果的tab导航和滚动导航的方法
- 关于JS中match() 和 exec() 返回值和属性的测试