Last active
March 15, 2024 12:24
-
-
Save dSalieri/2b616ff6bd09640e9846926f9882a206 to your computer and use it in GitHub Desktop.
Timer based on setTimeout
This file contains 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
/// Don't use interval less 5ms because web agents can't provide delay less than 4ms in due with optimization in nested setTimeout calls | |
/// But how the practice shows 5ms is lower border for this timer, because it accounts errors and evaluates corrected interval. That's is why 5ms the lowest interval of this timer. | |
function timer(callback, interval, duration, ...args) { | |
if (typeof callback !== "function") return; | |
const toNumberPositive = (value) => { | |
const n = Number(value); | |
return (n !== n || n < 0) ? 0 : n | |
}; | |
interval = (interval = toNumberPositive(interval)) >= 5 ? interval : 5; | |
duration = duration !== undefined ? toNumberPositive(duration) : Infinity; | |
const startTime = performance.now(); | |
let endInterval = startTime; | |
let timerId = null; | |
const step = () => { | |
const currentInterval = endInterval - startTime; | |
if (callback({currentInterval, interval, duration, args})) return; | |
if (interval > duration || currentInterval >= duration) return; | |
if (performance.now() >= (startTime + duration)) return; | |
const err = performance.now() - endInterval; | |
endInterval += interval; | |
timerId = setTimeout(step, interval - err); | |
} | |
step(); | |
return timerId !== null ? () => clearTimeout(timerId) : undefined; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment