Last active
July 25, 2021 19:00
-
-
Save dSalieri/c0a8e9a63e8000ab7bbfae89619e94a2 to your computer and use it in GitHub Desktop.
Timer based on requestAnimationFrame
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
/// 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