Created
December 26, 2023 01:32
-
-
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
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
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