Skip to content

Instantly share code, notes, and snippets.

@hkfoster
Created April 20, 2024 20:53
Show Gist options
  • Save hkfoster/edc05e9ad77b7294c7514c9fdd800300 to your computer and use it in GitHub Desktop.
Save hkfoster/edc05e9ad77b7294c7514c9fdd800300 to your computer and use it in GitHub Desktop.
A turnkey requestAnimationFrame replacement for setInterval
/**
* 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