Skip to content

Instantly share code, notes, and snippets.

@dSalieri
Last active March 15, 2024 12:24
Show Gist options
  • Save dSalieri/2b616ff6bd09640e9846926f9882a206 to your computer and use it in GitHub Desktop.
Save dSalieri/2b616ff6bd09640e9846926f9882a206 to your computer and use it in GitHub Desktop.
Timer based on setTimeout
/// 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