Skip to content

Instantly share code, notes, and snippets.

@NabiKAZ
Last active March 5, 2022 02:36
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 NabiKAZ/c2966fa6ad25f262c62874be24f12ff6 to your computer and use it in GitHub Desktop.
Save NabiKAZ/c2966fa6ad25f262c62874be24f12ff6 to your computer and use it in GitHub Desktop.
Delta Timing for JavaScript
/**
@author <a href="mailto:aaditmshah@myopera.com">Aadit M Shah</a>
@edited by <a href="mailto:nabikaz@gmail.com">NabiKAZ</a>
@overview Delta Timing for JavaScript.
@copyright 2012
@version 1.0.1
*/
/**
@description Creates a new Delta Timer with start and stop methods.
@constructor
@param {function} render The callback to render for animations.
@param {number} interval The interval of the timer in milliseconds.
*/
function DeltaTimer(render, interval) {
var timeout;
var lastTime;
this.start = start;
this.stop = stop;
this.setDelay = setDelay;
/**
@description Start the timer.
@public
@function
@returns {number} The UTC time in milliseconds when the timer started.
*/
function start() {
timeout = setTimeout(loop, 0);
lastTime = Date.now();
return lastTime;
}
/**
@description Stop the timer.
@public
@function
@returns {number} The UTC time in milliseconds when the timer stopped.
*/
function stop() {
clearTimeout(timeout);
return lastTime;
}
/**
@description Set new delay time.
@public
@function
@param {number} n The new interval of the timer in milliseconds.
*/
function setDelay(n) {
interval = n;
}
/**
@description Loop the timer continuously and call the render function.
@private
@function
*/
function loop() {
var thisTime = Date.now();
var deltaTime = thisTime - lastTime;
var delay = Math.max(interval - deltaTime, 0);
timeout = setTimeout(loop, delay);
lastTime = thisTime + delay;
render(thisTime);
}
}
@NabiKAZ
Copy link
Author

NabiKAZ commented Mar 5, 2022

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment