Created
February 6, 2018 03:39
-
-
Save leizongmin/58a2018b5a98152aae578489319c07d4 to your computer and use it in GitHub Desktop.
Node.js定时器测试代码
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 高精度定时器,interval为毫秒 | |
function myTimer(callback, interval) { | |
function getTime() { | |
return process.uptime() * 1000; | |
} | |
let previous = getTime(); | |
setInterval(function() { | |
const now = getTime(); | |
if (now - previous >= interval) { | |
previous = now; | |
callback(); | |
} | |
}, 0); | |
} | |
// 开始测试 | |
function test() { | |
let previous = process.uptime(); | |
myTimer(function() { | |
const now = process.uptime(); | |
console.log(now - previous); | |
previous = now; | |
}, 1000); | |
} | |
test(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let p = process.uptime(); | |
setInterval(function() { | |
const n = process.uptime(); | |
console.log(n - p); | |
p = n; | |
}, 1000); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment