网站首页 > 技术文章 正文
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);
本文参考资料:
- 上一篇: 太强了,竟然可以根据指纹图像预测性别
- 下一篇: 我的世界指令大全 minecraft常用命令汇总
猜你喜欢
- 2024-11-23 文件上传漏洞学习小结
- 2024-11-23 php手把手教你做网站(三十五)网站静态生成三实战标签的实现
- 2024-11-23 Html5方式打开三维CAD图纸,二维CAD图转三维CAD的详细教程
- 2024-11-23 用 Tensorflow.js 做了一个动漫分类的功能(一)
- 2024-11-23 Python可视化神器——pyecharts(实例之人口地图)
- 2024-11-23 PHP8中字符串与数组的转换-PHP8知识详解
- 2024-11-23 我的世界0.10.0作弊码介绍 minecraft作弊码分享
- 2024-11-23 我的世界创世神代码攻略大全
- 2024-11-23 我的世界指令大全 minecraft常用命令汇总
- 02-21走进git时代, 你该怎么玩?_gits
- 02-21GitHub是什么?它可不仅仅是云中的Git版本控制器
- 02-21Git常用操作总结_git基本用法
- 02-21为什么互联网巨头使用Git而放弃SVN?(含核心命令与原理)
- 02-21Git 高级用法,喜欢就拿去用_git基本用法
- 02-21Git常用命令和Git团队使用规范指南
- 02-21总结几个常用的Git命令的使用方法
- 02-21Git工作原理和常用指令_git原理详解
- 最近发表
- 标签列表
-
- cmd/c (57)
- c++中::是什么意思 (57)
- sqlset (59)
- ps可以打开pdf格式吗 (58)
- phprequire_once (61)
- localstorage.removeitem (74)
- routermode (59)
- vector线程安全吗 (70)
- & (66)
- java (73)
- org.redisson (64)
- log.warn (60)
- cannotinstantiatethetype (62)
- js数组插入 (83)
- resttemplateokhttp (59)
- gormwherein (64)
- linux删除一个文件夹 (65)
- mac安装java (72)
- reader.onload (61)
- outofmemoryerror是什么意思 (64)
- flask文件上传 (63)
- eacces (67)
- 查看mysql是否启动 (70)
- java是值传递还是引用传递 (58)
- 无效的列索引 (74)