网站首页 > 知识剖析 正文
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);
本文参考资料:
- 上一篇: 如何在Spring Boot接口中解决防抖问题?
- 下一篇: Node.js 的事件循环机制
猜你喜欢
- 2025-05-15 英文美文分享: The Power of Time Management (时间管理的力量)
- 2025-05-15 高考热点accident、incident以及event辨析
- 2025-05-15 手把手教你实现振动记录器
- 2025-05-15 面试官:你知道websocket的心跳机制吗?
- 2025-05-15 Nike Zoom Clear Out (正式发布多图)品鉴
- 2025-05-15 初中7~9年级所有动词短语汇总(附习题及解析)
- 2025-05-15 1分钟搞懂防抖和节流
- 2025-05-15 手把手教你写一个简易的微前端框架
- 2025-05-15 Node.js 是如何跑起来的
- 2025-05-15 setTimeout 和 setInterval 的区别,包含内存方面的分析
- 最近发表
- 标签列表
-
- xml (46)
- css animation (57)
- array_slice (60)
- htmlspecialchars (54)
- position: absolute (54)
- datediff函数 (47)
- array_pop (49)
- jsmap (52)
- toggleclass (43)
- console.time (63)
- .sql (41)
- ahref (40)
- js json.parse (59)
- html复选框 (60)
- css 透明 (44)
- css 颜色 (47)
- php replace (41)
- css nth-child (48)
- min-height (40)
- xml schema (44)
- css 最后一个元素 (46)
- location.origin (44)
- table border (49)
- html tr (40)
- video controls (49)