1
0
mirror of https://github.com/wbbaddons/Tims-Chat.git synced 2024-11-19 17:00:08 +00:00
Tims-Chat/files_wcf/js/Bastelstu.be/Chat/DataStructure/Throttle.js

100 lines
1.9 KiB
JavaScript
Raw Normal View History

2018-08-16 22:30:59 +00:00
/*
2021-02-04 22:04:35 +00:00
* Copyright (c) 2010-2021 Tim Düsterhus.
2018-08-16 22:30:59 +00:00
*
* Use of this software is governed by the Business Source License
* included in the LICENSE file.
*
2021-03-05 16:19:27 +00:00
* Change Date: 2025-03-05
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
})