Created
April 20, 2024 20:53
-
-
Save hkfoster/edc05e9ad77b7294c7514c9fdd800300 to your computer and use it in GitHub Desktop.
A turnkey requestAnimationFrame replacement for setInterval
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
/** | |
* Interval 0.0.2 | |
* A turnkey requestAnimationFrame replacement for setInterval | |
* @author Kyle Foster (@hkfoster) | |
* @license MIT | |
**/ | |
const interval = { | |
set: (fn, delay) => { | |
if (!window.requestAnimationFrame) return window.setInterval(fn, delay) | |
let start = new Date().getTime() | |
const handle = {} | |
const loop = () => { | |
const current = new Date().getTime() | |
const delta = current - start | |
if(delta >= delay) { | |
fn.call() | |
start = new Date().getTime() | |
} | |
handle.value = requestAnimationFrame(loop) | |
} | |
handle.value = requestAnimationFrame(loop) | |
return handle | |
}, | |
clear: (handle) => { | |
if (!window.cancelAnimationFrame) return clearInterval(handle) | |
window.cancelAnimationFrame(handle.value) | |
} | |
} | |
export default interval |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment