Last active
March 5, 2022 02:36
-
-
Save NabiKAZ/c2966fa6ad25f262c62874be24f12ff6 to your computer and use it in GitHub Desktop.
Delta Timing for JavaScript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
@author <a href="mailto:[email protected]">Aadit M Shah</a> | |
@edited by <a href="mailto:[email protected]">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); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Sample Code: https://jsfiddle.net/NabiKAZ/ejtL16s5/