NodeJS中使用事件监听器定时器和回调

一。用时间间隔执行定期工作 setInterval

      /**
         * To schedule the repeated execution of <i><code>callback</code></i> every <i><code>delay</code></i> milliseconds. <p>
         * Returns a <i><code>intervalObject</code></i> for possible use with <i><code>clearInterval()</code></i>. Optionally you can also pass arguments to the callback.
         *
         * @param {Function} callback
         * @param {number} delay
         * @param {...*} args
         * @return {Object}
         */
        function setInterval(callback, delay, args) {
        }
        
        
        var x = 0, y = 0, z = 0;
        function dipalyValues() {
            console.log("X=%d;Y=%d;Z=%d", x, y, z);
        }
        function updateX() {
            x+=1;
        }
        function updateY() {
            y +=1;
        }
        function updateZ() {
            z+=1;
            dipalyValues();
        }
        setInterval(updateX, 500);
        setInterval(updateY, 1000);
        setInterval(updateZ, 2000);

结果

结果

二。用超时时间来延迟工作 setTimerout

    /**
     * To schedule execution of a one-time <i><code>callback</code></i> after <i><code>delay</code></i> milliseconds.<p>
     * Returns a <i><code>timeoutObject</code></i> for possible use with <i><code>clearTimeout()</code></i>. Optionally you can also pass arguments to the callback.
     * <p>
     * It is important to note that your callback will probably not be called in exactly <i><code>delay</code></i> milliseconds - Node.js makes no guarantees about the exact timing of when the callback will fire, nor of the ordering things will fire in. The callback will be called as close as possible to the time specified.
     * @param {Function} callback
     * @param {number} delay
     * @param {...*} args
     * @return {Object}
     */
    function setTimeout(callback, delay, args) {
    }
    
    function simpelTimeOut(consoleTimer) {
        console.timeEnd(consoleTimer);
    }
    console.time("twoSecond");
    setTimeout(simpelTimeOut, 2000, "twoSecond");
    console.time("oneSecond");
    setTimeout(simpelTimeOut, 1000, "oneSecond");
    console.time("fiveSecond");
    setTimeout(simpelTimeOut, 5000, "fiveSecond");
    console.time("50MinlliSecond");
    setTimeout(simpelTimeOut, 50, "50MinlliSecond");

结果

结果这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值