simple vainilla JS util to call a function each N milliseconds
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
const loop = { | |
timer: null, | |
count: 0, | |
start(fn, time=1000, limit = 100) { | |
fn(this.stop.bind(this), this.count); | |
this.count++; | |
if (this.count < limit) { | |
this.timer = setTimeout(() => this.start(fn, time, limit), time) | |
} else { | |
this.stop() | |
} | |
}, | |
reset() { this.count = 0 }, | |
stop() { | |
clearTimeout(this.timer); | |
this.reset() | |
} | |
} | |
// usage: | |
function fn(stop, count) { | |
console.log(`time: ${count}`) | |
// if (sth) stop() | |
} | |
// default 1000 ms | |
loop.start(fn) | |
// each 500 ms | |
loop.start(fn, 500) | |
// only 10 times | |
loop.start(fn, 500, 10) | |
// also in any moment one can run: | |
loop.stop() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment