setTimeout

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

一个简单的例子:

Node.js实战6:定时器,使用timer延迟执行。-LMLPHP
console.log( (new Date()).getSeconds() );setTimeout(function(){

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

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

执行效果:

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

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

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

bind

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

Node.js实战6:定时器,使用timer延迟执行。-LMLPHP
function bomb(){ this.message = "bomb";}

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

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

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

执行效果:

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

clearTimeout

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

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

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

将上面的代码稍做修改:

Node.js实战6:定时器,使用timer延迟执行。-LMLPHP
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,可以不停的按时间间隔循环执行。

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

执行效果:

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

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

Node.js实战6:定时器,使用timer延迟执行。-LMLPHP
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延迟执行。-LMLPHP
 
05-29 01:11