Skip to content

Instantly share code, notes, and snippets.

@electerious
Last active February 15, 2021 02:33
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save electerious/6b7002baacdefc071a981cf796415268 to your computer and use it in GitHub Desktop.
Save electerious/6b7002baacdefc071a981cf796415268 to your computer and use it in GitHub Desktop.
Function that continuously executes the function it has been most recently called with
const single = (max) => {
let id
let iterations
const loop = (_id, fn) => {
if (id!==_id) return
if (max!==undefined && iterations>=max) return
++iterations
fn()
requestAnimationFrame(() => loop(_id, fn))
}
return (fn) => {
id = Symbol()
iterations = 0
loop(id, fn)
return () => id = Symbol()
}
}
@electerious
Copy link
Author

electerious commented Aug 13, 2017

Example:

const run = single()

run(() => console.log(1)) // Logs 1 till the next line has been executed
run(() => console.log(2)) // Logs 2 forever
const run = single()
let stop

stop = run(() => console.log(1)) // Logs 1 till the next line has been executed
stop = run(() => console.log(2)) // Logs 2 till the returned function has been executed

stop()
const run = single(5)

run(() => console.log(1)) // Never executes more than 5 times

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment