Skip to content

Commit

Permalink
Freeze time in the background.
Browse files Browse the repository at this point in the history
Rather than periodically flushing the timer queue in the background, freeze time
such that timers remain blissfully unaware of their sleep when returning to the
foreground. Fixes d3/d3-transition#29.
  • Loading branch information
mbostock committed Feb 11, 2016
1 parent e6e92dc commit da49992
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 9 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "d3-timer",
"version": "0.3.1",
"version": "0.3.2",
"description": "An efficient queue capable of managing thousands of concurrent animations.",
"keywords": [
"d3",
Expand Down
16 changes: 8 additions & 8 deletions src/timer.js
Original file line number Diff line number Diff line change
@@ -1,16 +1,17 @@
var frame = 0, // is an animation frame pending?
timeout = 0, // is a timeout pending?
interval = 0, // are any timers active?
maxDelay = 5000, // the longest we’ll sleep if there are active timers
pokeDelay = 1000, // how frequently we check for clock skew
taskHead,
taskTail,
clockLast = 0,
clockNow = 0,
clockSkew = 0,
clock = typeof performance === "object" ? performance : Date,
setFrame = typeof requestAnimationFrame === "function" ? requestAnimationFrame : function(callback) { return setTimeout(callback, 17); };

export function now() {
return clockNow || (setFrame(clearNow), clockNow = clock.now());
return clockNow || (setFrame(clearNow), clockNow = clock.now() + clockSkew);
}

function clearNow() {
Expand Down Expand Up @@ -69,7 +70,7 @@ export function timerFlush() {
}

function wake(time) {
clockLast = clockNow = time || clock.now();
clockNow = (clockLast = time || clock.now()) + clockSkew;
frame = timeout = 0;
try {
timerFlush();
Expand All @@ -81,9 +82,8 @@ function wake(time) {
}

function poke() {
if (clock.now() - clockLast > maxDelay) {
wake();
}
var now = clock.now(), delay = now - clockLast;
if (delay > pokeDelay) clockSkew -= delay, clockLast = now;
}

function nap() {
Expand All @@ -106,9 +106,9 @@ function sleep(time) {
var delay = time - clockNow;
if (delay > 24) {
if (time < Infinity) timeout = setTimeout(wake, delay);
else if (interval) interval = clearInterval(interval);
if (interval) interval = clearInterval(interval);
} else {
if (!interval) interval = setInterval(poke, maxDelay);
if (!interval) interval = setInterval(poke, pokeDelay);
frame = 1, setFrame(wake);
}
}

0 comments on commit da49992

Please sign in to comment.