Skip to content

Instantly share code, notes, and snippets.

@sbisbee
Created March 7, 2016 16:48
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 sbisbee/be49a454eabc286ac532 to your computer and use it in GitHub Desktop.
Save sbisbee/be49a454eabc286ac532 to your computer and use it in GitHub Desktop.
/*
* Demo of causing timer drift due to node's single threaded nature and the
* underlying timer implementation (each timer period, TIMER_MS, gets its own
* linked list that is invoked serially).
*
* This demo uses a sync block in fnOne(), but you can imagine a scenario where
* you have too many timers performing both sync and async operations that
* would cause a similar behavior. This can become a problem when you need
* timer driven calculations to be completed inside of a window and/or rely on
* current system time to determine a time window to insert data into.
*
* For example, if fnTwo() below relied on current system time to pick a bucket
* to store data into and the bucket window size was <=SYNC_BLOCK_MS, then its
* calculation would be off by one bucket.
*
* Example run:
* ```
* $ node ./run.js
* Starting 1457369073641
* Done 1457369083641
* ms drift 10002
* ```
*
* Rabbit hole entrance:
* https://github.com/nodejs/node/blob/master/lib/timers.js#L14
* https://github.com/nodejs/node/blob/master/lib/timers.js#L114
*/
var SYNC_BLOCK_MS = 10000;
var TIMER_MS = 100;
//emulate a sync block
var fnOne = function() {
var start = new Date().getTime();
var end = start + SYNC_BLOCK_MS;
console.log('Starting\t', start);
while(new Date().getTime() < end);
}
var fnTwo = function() {
var actualTime = new Date().getTime();
var drift = actualTime - expectedTime;
console.log('Done\t\t', actualTime);
console.log('ms drift\t', drift);
};
//roughly when we expect both functions to fire
var expectedTime = new Date().getTime() + TIMER_MS;
//both functions are in the same timer ms list, which appends
setTimeout(fnOne, TIMER_MS);
setTimeout(fnTwo, TIMER_MS);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment