快速掌握Node.js中setTimeout和setInterval的使用方法

字號:


    這篇文章主要為大家介紹了快速掌握Node.js中setTimeout和setInterval的使用方法,感興趣的小伙伴們可以參考一下
    Node.js和js一樣也有計時器,超時計時器、間隔計時器、及時計時器,它們以及process.nextTick(callback)函數(shù)來實現(xiàn)事件調度。今天先學下setTimeout和setInterval的使用。
    一、setTimeout超時計時器(和GCD中的after類似)
    在node.js中可以使用node.js內(nèi)置的setTimeout(callback,delayMillSeconds,[args])方法。當調用setTime()時回調函數(shù)會在delayMillSeconds后
    執(zhí)行.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);這行注釋之后可以看到是會執(zhí)行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類似)
    間隔計時器用來按定期的時間間隔來執(zhí)行工作.和setTimeout類似,node.js中內(nèi)置setInterval(callback,delayMilliSecond,[args])來創(chuàng)建并返回定時器對象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);
    上面代碼是創(chuàng)建setInterval的回調函數(shù)myfunc,參數(shù)為Interval,setInterval每隔1s執(zhí)行一次,setTimeout是在5秒之后執(zhí)行,它的回調函數(shù)讓間隔計時器取消。
    "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
    三、從事件循環(huán)中取消定時器引用
    當事件隊列中僅存在定時器回調函數(shù)時,如果不希望再執(zhí)行它們,可以使用setInterval和setTimeout返回對象的unref()函數(shù)來通知事件循環(huán)不要繼續(xù)。
    當unref()和setTimeout結合使用,要用獨立計時器來喚醒事件循環(huán),大量使用對性能也會產(chǎn)生影響,應盡量少用。
    四、setTimeout和setInterval執(zhí)行時間是不精確的
    它們是間隔一定時間將回調添加到事件隊列中,執(zhí)行也不是太精確
    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");
    以上代碼多執(zhí)行幾次輸出的結果也是不一樣的。
    "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
    以上就是本文的全部內(nèi)容,希望對大家學習Node.js中setTimeout和setInterval的使用方法有所幫助。