Skip to content

Instantly share code, notes, and snippets.

@leizongmin
Created February 6, 2018 03:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save leizongmin/58a2018b5a98152aae578489319c07d4 to your computer and use it in GitHub Desktop.
Save leizongmin/58a2018b5a98152aae578489319c07d4 to your computer and use it in GitHub Desktop.
Node.js定时器测试代码
// 高精度定时器,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();
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