Skip to content

Instantly share code, notes, and snippets.

@myndzi
Last active October 14, 2017 20:07
Show Gist options
  • Save myndzi/208fa0164449105fc6c4a0082228865d to your computer and use it in GitHub Desktop.
Save myndzi/208fa0164449105fc6c4a0082228865d to your computer and use it in GitHub Desktop.
'use strict';
var WINDOW = Math.pow(2,11)-1;
function time() {
var hrtime = process.hrtime();
return (hrtime[0] * 1e3) + ((hrtime[1] / 1e6)|0);
}
function setPedanticInterval(cb, ival) {
if (ival > WINDOW / 2) {
throw new Error('Interval '+ival+' is greater than half the window size ('+WINDOW+')');
}
var nextTime = time();
function tick() {
// skip first execution
if (arguments.length === 0) { cb(); }
var now = time() & WINDOW;
nextTime = (nextTime + ival) & WINDOW;
var delay = (nextTime < now ?
WINDOW + nextTime - now :
nextTime - now
);
console.log('>>', nextTime, delay);
setTimeout(tick, delay);
}
tick(1);
}
setPedanticInterval(function () { console.log(Date.now()); }, 1000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment