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");
结果
。