龙空技术网

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

JShaman 489

前言:

而今兄弟们对“js循环定时器”大约比较着重,姐妹们都想要知道一些“js循环定时器”的相关内容。那么小编同时在网摘上搜集了一些有关“js循环定时器””的相关知识,希望大家能喜欢,姐妹们一起来学习一下吧!

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);

本文参考资料:

标签: #js循环定时器