首页 > Web开发 > 详细

Node.js实战6:定时器,使用timer延迟执行。

时间:2019-12-09 10:05:18      阅读:78      评论:0      收藏:0      [点我收藏+]

setTimeout

在nodejs中,通过setTimeout函数可以达到延迟执行的效果,这个函数也常被称为定时器。

一个简单的例子:

技术分享图片
console.log( (new Date()).getSeconds() );
setTimeout(function(){

console.log( (new Date()).getSeconds() );
console.log("hello world");

//延迟一秒执行
},1000);

执行效果:

技术分享图片

可以看到,执行时,先输出了当时时间的秒数,过1秒后,输入出秒和hello world,间隔正是1秒。上面的参数中1000,单位是毫秒,即1秒。

在nodejs中,常用setTimeout来实现异步操作。

bind

还有一种高级的用法,看例程:

技术分享图片
function bomb(){
this.message = "bomb";
}

bomb.prototype.explode =function(){
console.log(this.message);
}

var bomb = new bomb();
setTimeout(bomb.explode.bind(bomb),1000);

即:使用bind可以确保这个方法绑定到正确的对象上,这样可以访问到这个对象的内部属性。

执行效果:

技术分享图片

clearTimeout

通过clearTimeout函数,可以清除掉定时器。

比如说setTimeout设定了一个定时器,将在1秒后触发某个操作,如果在未触发之前,

clearTimeout函数取消这个定时器操作。

将上面的代码稍做修改:

技术分享图片
function bomb(){
this.message = "bomb";
}

bomb.prototype.explode =function(){
console.log(this.message);
}

var bomb = new bomb();
var timeoutid = setTimeout(bomb.explode.bind(bomb),1000);

//取消定时器
clearTimeout(timeoutid);

这样,就不会触发1秒后的操作。

setInterval

setTimerout,会延时一定时间后执行一个操作,只执行一次。

而setInterval,可以不停的按时间间隔循环执行。

技术分享图片

执行效果:

技术分享图片

循环执行到什么时候呢?直到程序退出,或直到使用clearInterval()函数取消这个定时器。

技术分享图片
console.log( (new Date()).getSeconds() );
var interval_id = setInterval(function(){

console.log( (new Date()).getSeconds() );
console.log("hello world");

},1000);
clearInterval(interval_id);

本文参考资料:

技术分享图片

Node.js实战6:定时器,使用timer延迟执行。

原文:https://www.cnblogs.com/w2sft/p/12008923.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!