Node.js和js一样也有计时器,超时计时器、间隔计时器、及时计时器,它们以及process.nextTick(callback)函数来实现事件调度。今天先学下setTimeout和setInterval的使用。

一、setTimeout超时计时器(和GCD中的after类似)

在node.js中可以使用node.js内置的setTimeout(callback,delayMillSeconds,[args])方法。当调用setTime()时回调函数会在delayMillSeconds后

执行.setTime() 会返回一个定时器对象ID,可以在delayMillSeconds到期前将ID传给clearTimeout(timeoutId)来取消。

function  myfunc(){
    console.log("myfunc");
};
var mytimeout=setTimeout(myfunc,1000);
clearTimeout(mytimeout);
"C:\Program Files (x86)\JetBrains\WebStorm 11.0.3\bin\runnerw.exe" F:\nodejs\node.exe timer.js

Process finished with exit code 0

如果将clearTimeout(mytimeout);这行注释之后可以看到是会执行myfunc()。

"C:\Program Files (x86)\JetBrains\WebStorm 11.0.3\bin\runnerw.exe" F:\nodejs\node.exe timer.js
myfunc

Process finished with exit code 0

二、setInterval间隔计时器(和GCD中的dispatch_source_t或NSTimer类似)

间隔计时器用来按定期的时间间隔来执行工作.和setTimeout类似,node.js中内置setInterval(callback,delayMilliSecond,[args])来创建并返回定时器对象Id,通过clearInterval()来取消。

/**
 * Created by Administrator on 2016/3/11.
 */
function  myfunc(Interval){
    console.log("myfunc  "+Interval);
}
var myInterval=setInterval(myfunc,1000,"Interval");
function  stopInterval(){
    clearTimeout(myInterval);
 //myInterval.unref();
}
setTimeout(stopInterval,5000);

上面代码是创建setInterval的回调函数myfunc,参数为Interval,setInterval每隔1s执行一次,setTimeout是在5秒之后执行,它的回调函数让间隔计时器取消。

"C:\Program Files (x86)\JetBrains\WebStorm 11.0.3\bin\runnerw.exe" F:\nodejs\node.exe Interval.js
myfunc  Interval
myfunc  Interval
myfunc  Interval
myfunc  Interval

Process finished with exit code 0

三、从事件循环中取消定时器引用

当事件队列中仅存在定时器回调函数时,如果不希望再执行它们,可以使用setInterval和setTimeout返回对象的unref()函数来通知事件循环不要继续。

当unref()和setTimeout结合使用,要用独立计时器来唤醒事件循环,大量使用对性能也会产生影响,应尽量少用。

四、setTimeout和setInterval执行时间是不精确的

它们是间隔一定时间将回调添加到事件队列中,执行也不是太精确

function  simpleTimeout(consoleTime)
{
    console.timeEnd(consoleTime);
}
console.time("twoSecond");
setTimeout(simpleTimeout,2000,"twoSecond");

console.time("oneSecond");
setTimeout(simpleTimeout,1000,"oneSecond");

console.time("fiveSecond");
setTimeout(simpleTimeout,5000,"fiveSecond");

console.time("50MillSecond");
setTimeout(simpleTimeout,50,"50MillSecond");

以上代码多执行几次输出的结果也是不一样的。

"C:\Program Files (x86)\JetBrains\WebStorm 11.0.3\bin\runnerw.exe" F:\nodejs\node.exe timer.js
50MillSecond: 51ms
oneSecond: 1000ms
twoSecond: 2002ms
fiveSecond: 5001ms

Process finished with exit code 0

Node.js中setTimeout和setInterval的使用的更多相关文章

  1. 【转】JS中setTimeout和setInterval的最大延时值详解

    前言 JavaScript提供定时执行代码的功能,叫做定时器(timer),主要由setTimeout()和setInterval()这两个函数来完成.而这篇文中主要给大家介绍的是关于JS中setTi ...

  2. js中setTimeout和setInterval的应用方法(转)

    JS里设定延时: 使用SetInterval和设定延时函数setTimeout 很类似.setTimeout 运用在延迟一段时间,再进行某项操作. setTimeout("function& ...

  3. JS中SetTimeOut和SetInterval方法的区别?

    1.setInterval() 方法可按照指定的周期(以毫秒计)来调用函数或计算表达式. setInterval() 方法会不停地调用函数,直到 clearInterval() 被调用或窗口被关闭.由 ...

  4. js中setTimeout、setInterval、 clearInterval方法简介

    setTimeout setTimeout(code, millisec) 用于在指定的毫秒数后调用函数或计算表达式. 说明: setTimeout()只执行一次code.如果要多次调用,要使用set ...

  5. js中setTimeout/setInterval定时器用法示例

    js中setTimeout(定时执行一次)和setInterval(间隔循环执行)用法介绍. setTimeout:在指定的毫秒数后调用指定的代码段或函数:setTimeout示例代码 functio ...

  6. node.js中对 redis 的安装和基本操作

    一.win下安装redis https://github.com/MicrosoftArchive/redis/releases 下载Redis-x64-3.2.100.zip,然后解压,放到自定义目 ...

  7. 【nodejs原理&源码赏析(7)】【译】Node.js中的事件循环,定时器和process.nextTick

    [摘要] 官网博文翻译,nodejs中的定时器 示例代码托管在:http://www.github.com/dashnowords/blogs 原文地址:https://nodejs.org/en/d ...

  8. 【nodejs原理&源码赏析(7)】【译】Node.js中的事件循环,定时器和process.nextTick

    目录 Event Loop 是什么? Event Loop 基本解释 事件循环阶段概览 事件循环细节 timers pending callbacks poll阶段 check close callb ...

  9. 在Node.js中使用RabbitMQ系列二 任务队列

    在上一篇文章在Node.js中使用RabbitMQ系列一 Hello world我有使用一个任务队列,不过当时的场景是将消息发送给一个消费者,本篇文章我将讨论有多个消费者的场景. 其实,任务队列最核心 ...

随机推荐

  1. supervisord 启动失败 Error: Another program is already listening on a port that one of our HTTP serve...

    Linux系统中 Supervisor 配置守护进程: 启动Supervisor 服务语句: supervisord -c /etc/supervisor/supervisord.conf 这个过程可 ...

  2. .net Framework使用之 MongoDB

    新建Helper using MongoDB.Bson; using MongoDB.Driver; using System; using System.Collections.Generic; u ...

  3. OCP 12c 062题库大更新,出现大量新题-5

    5.One of your databases supports an OLTP workload. The default undo tablespace is fixed size with: 1 ...

  4. http 协议 c++代码 获取网页

    最近接触了些 html 和 JavaScript,索性了解下 http 协议.在园子里找到了 HTTP协议详解,图文并茂,很爽! 于是小小的尝试了下 #include <WinSock2.h&g ...

  5. Java之常用类库

    1.Java常用类库(一):http://blog.csdn.net/e6894853/article/details/7925469 1.Java常用类库(二):http://blog.csdn.n ...

  6. 解决 ArchLinux 下中文 Chinese 不能输入 couldnt input 的问题

    解决 ArchLinux 下中文 Chinese 不能输入 couldnt input 的问题 一.Question 一年多的 ArchLinux 用户再次回归.然鹅,见面礼就是终端不能输入中文. 在 ...

  7. ReentrantLock总体概括

    一.锁的实现原理: JAVA concurrent包下面的锁是通过AbstractQueuedSynchronizer内的Node类下面的state属性来实现的,并且锁的可重入属性也是通过state实 ...

  8. MyEclipse配置Hibernate具体步骤

    工具: MyEclipse,MySQL 步骤: 1.打开MyEclipse,新建一个Java Project(取名:h1) 2.创建MySQL数据库 3.找到MyEclipse下的MyEclipse ...

  9. 了解ORACLE培训OCA-OCP-OCM课程表

    了解ORACLE培训OCA-OCP-OCM课程表考试号: OCA    1Z0-007$125    Oracle Database 10g:SQL Fundamentals 本课程培养学生必要的SQ ...

  10. POJ 1050

    #include <stdio.h> #include <string.h> #define mt 101 int main() { int a[mt][mt]; int st ...