Skip to content

Instantly share code, notes, and snippets.

@jnpn
Created December 26, 2023 01:32
Show Gist options
  • Save jnpn/567ba379f437f3a0c04f2269dc0c4850 to your computer and use it in GitHub Desktop.
Save jnpn/567ba379f437f3a0c04f2269dc0c4850 to your computer and use it in GitHub Desktop.
js class to wrap setinterval and make a start/stopable thunk with ~private state
class Repeated {
constructor(delay, cond, fn, state) {
this.delay = delay;
this.cond = cond;
this.fn = fn;
this.state = state;
this.timer = null;
this.timers = [];
}
fun() {
return () => {
console.log('fun');
if (this.cond(this.state)) {
console.log('fun', 'stop');
this.stop();
return this.state;
} else {
console.log('fun', 'go');
this.fn(this.state);
}
}
}
start () {
let code = this.fun();
console.debug('start', code)
this.timer = setInterval(code, this.delay)
}
stop () {
console.debug('stop')
if (this.timer) {
clearInterval(this.timer);
this.timers.push(this.timer);
this.timer = null;
} else {
console.debug('[invalid state]', this.timer, 'should not be null');
}
}
}
function todo () {
console.log('?', new Date());
document.body.innerHTML = new Date();
}
r = new Repeated(1000, s => s.stop === true, todo, { stop : false })
r.start()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment