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

setTimeout

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

一个简单的例子:

c971b6ea86af49f6ba16f64bb98e5e22.png
console.log( (new Date()).getSeconds() );setTimeout(function(){ console.log( (new Date()).getSeconds() ); console.log("hello world"); //延迟一秒执行},1000);

执行效果:

78cb3aba14dfee67d02c0a108567c48b.png

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

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

bind

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

fdf217cf5f8fa70b881c5cac933e9898.png
function bomb(){ this.message = "bomb";}bomb.prototype.explode =function(){ console.log(this.message);}var bomb = new bomb();setTimeout(bomb.explode.bind(bomb),1000);

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

执行效果:

80b5e1182d8c76871003363416759f63.png

clearTimeout

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

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

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

将上面的代码稍做修改:

28b94a15218f6dd4958178933d84ee63.png
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,可以不停的按时间间隔循环执行。

9301f07bbf9fd6b4d6b276d5859afe56.png

执行效果:

b952405c688b039398f09becf16f339f.png

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

35459351f41238661ecec6b69e2c884c.png
console.log( (new Date()).getSeconds() );var interval_id = setInterval(function(){ console.log( (new Date()).getSeconds() ); console.log("hello world"); },1000);clearInterval(interval_id);

本文参考资料:

404bb59256cd2021660ed5eae047e0fe.png
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值