Skip to content

Instantly share code, notes, and snippets.

@dSalieri
Last active July 25, 2021 19:00
Show Gist options
  • Save dSalieri/c0a8e9a63e8000ab7bbfae89619e94a2 to your computer and use it in GitHub Desktop.
Save dSalieri/c0a8e9a63e8000ab7bbfae89619e94a2 to your computer and use it in GitHub Desktop.
Timer based on requestAnimationFrame
/// If you will use extremely low values, actual interval will be equal to 1000/HZ of your monitor in the other case interval will be equal to settled by you
function rafTimer(callback, interval, duration) {
interval = interval || 1;
duration = duration || Infinity;
let startTime = performance.now();
let endInterval = startTime;
let removeId = null;
(function step() {
let endIntervalStep = endInterval - startTime;
let currentInterval = performance.now() - startTime;
if (currentInterval >= endIntervalStep) {
let dynamiclyInterval = (currentInterval - endIntervalStep) < interval
? endIntervalStep
: currentInterval < duration
? Math.floor(currentInterval)
: duration;
if(callback(dynamiclyInterval, duration, interval)) return;
endInterval += interval;
}
if (currentInterval <= duration) {
removeId = requestAnimationFrame(step);
}
})();
return function () {
cancelAnimationFrame(removeId);
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment