2018-08-16 22:30:59 +00:00
|
|
|
/*
|
|
|
|
* Copyright (c) 2010-2018 Tim Düsterhus.
|
|
|
|
*
|
|
|
|
* Use of this software is governed by the Business Source License
|
|
|
|
* included in the LICENSE file.
|
|
|
|
*
|
2020-11-19 23:08:57 +00:00
|
|
|
* Change Date: 2024-11-20
|
2018-08-16 22:30:59 +00:00
|
|
|
*
|
|
|
|
* On the date above, in accordance with the Business Source
|
|
|
|
* License, use of this software will be governed by version 2
|
|
|
|
* or later of the General Public License.
|
|
|
|
*/
|
|
|
|
|
2020-11-01 16:41:19 +00:00
|
|
|
define([], function () {
|
|
|
|
'use strict'
|
2018-08-16 22:30:59 +00:00
|
|
|
|
|
|
|
class Throttler {
|
|
|
|
constructor(callback, delay = 125) {
|
|
|
|
if (!(typeof callback === 'function')) {
|
|
|
|
throw new Error('Callback must be a function.')
|
|
|
|
}
|
|
|
|
if (delay < 0) {
|
|
|
|
throw new Error('Delay must be non-negative.')
|
|
|
|
}
|
|
|
|
|
|
|
|
this.callback = callback
|
|
|
|
this._delay = delay
|
|
|
|
|
|
|
|
this.hot = false
|
|
|
|
this.awaiting = false
|
|
|
|
this.timer = null
|
|
|
|
this.last = Date.now()
|
|
|
|
}
|
|
|
|
|
|
|
|
setTimer() {
|
|
|
|
if (this.timer != null) {
|
|
|
|
clearTimeout(this.timer)
|
|
|
|
}
|
|
|
|
|
2020-11-01 16:41:19 +00:00
|
|
|
this.timer = setTimeout((_) => {
|
2018-08-16 22:30:59 +00:00
|
|
|
this.timer = null
|
|
|
|
this.hot = false
|
|
|
|
|
|
|
|
if (this.awaiting) {
|
|
|
|
this.execute()
|
|
|
|
}
|
|
|
|
}, this.delay)
|
|
|
|
}
|
|
|
|
|
|
|
|
execute() {
|
|
|
|
this.awaiting = false
|
|
|
|
this.hot = true
|
|
|
|
|
|
|
|
this.last = Date.now()
|
|
|
|
|
|
|
|
this.setTimer()
|
|
|
|
this.callback()
|
|
|
|
}
|
|
|
|
|
|
|
|
guardedExecute() {
|
|
|
|
if (this.hot) {
|
|
|
|
this.awaiting = true
|
2020-11-01 16:41:19 +00:00
|
|
|
} else {
|
2018-08-16 22:30:59 +00:00
|
|
|
this.execute()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
get delay() {
|
|
|
|
return this._delay
|
|
|
|
}
|
|
|
|
|
|
|
|
set delay(newDelay) {
|
2020-11-01 16:41:19 +00:00
|
|
|
if (this.awaiting && Date.now() - this.last > newDelay) {
|
2018-08-16 22:30:59 +00:00
|
|
|
this._delay = 0
|
|
|
|
this.setTimer()
|
2020-11-01 16:41:19 +00:00
|
|
|
} else if (this.timer) {
|
2018-08-16 22:30:59 +00:00
|
|
|
this._delay = Math.max(0, newDelay - (Date.now() - this.last))
|
|
|
|
this.setTimer()
|
|
|
|
}
|
|
|
|
|
|
|
|
this._delay = newDelay
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
const throttle = function (callback, delay = 125) {
|
|
|
|
const throttler = new Throttler(callback, delay)
|
|
|
|
const result = throttler.guardedExecute.bind(throttler)
|
|
|
|
result.setDelay = function (newDelay) {
|
|
|
|
throttler.delay = newDelay
|
|
|
|
}
|
|
|
|
result.getDelay = function () {
|
|
|
|
return throttler.delay
|
|
|
|
}
|
|
|
|
|
|
|
|
return result
|
|
|
|
}
|
|
|
|
|
|
|
|
return throttle
|
2020-11-01 16:41:19 +00:00
|
|
|
})
|