Debouncer example

node v8.17.0
version: 1.0.0
endpointsharetweet
class Debouncer { constructor (fn, timeout) { this.fn = fn this.timeout = timeout this.pile = [] this.working = false } execute () { if (this.working) return this.working = true this.pile = [] this.fn(() => { setTimeout(() => { this.working = false this.tryExecute() }, this.timeout) }) } tryExecute () { if (this.pile.length === 0) return this.execute() } touch () { this.pile.push(true) this.tryExecute() } } const debounce = new Debouncer((cb) => { console.log('calling this fn') cb() }, 1000) const a = [1,2,3,4,5,6,7,8,9,10] a.forEach(i => { debounce.touch() })
Loading…

no comments

    sign in to comment