chore(client/ts): port services/debounce

This commit is contained in:
Elian Doran 2024-12-21 17:00:36 +02:00
parent 911323c099
commit 7fc4443206
No known key found for this signature in database

View File

@ -7,13 +7,17 @@
* *
* @source underscore.js * @source underscore.js
* @see http://unscriptable.com/2009/03/20/debouncing-javascript-methods/ * @see http://unscriptable.com/2009/03/20/debouncing-javascript-methods/
* @param {Function} func to wrap * @param func to wrap
* @param {Number} waitMs in ms (`100`) * @param waitMs in ms (`100`)
* @param {Boolean} [immediate=false] whether to execute at the beginning (`false`) * @param whether to execute at the beginning (`false`)
* @api public * @api public
*/ */
function debounce(func, waitMs, immediate = false) { function debounce<T>(func: (...args: unknown[]) => T, waitMs: number, immediate: boolean = false) {
let timeout, args, context, timestamp, result; let timeout: any; // TODO: fix once we split client and server.
let args: unknown[] | null;
let context: unknown;
let timestamp: number;
let result: T;
if (null == waitMs) waitMs = 100; if (null == waitMs) waitMs = 100;
function later() { function later() {
@ -24,20 +28,20 @@ function debounce(func, waitMs, immediate = false) {
} else { } else {
timeout = null; timeout = null;
if (!immediate) { if (!immediate) {
result = func.apply(context, args); result = func.apply(context, args || []);
context = args = null; context = args = null;
} }
} }
} }
const debounced = function () { const debounced = function (this: any) {
context = this; context = this;
args = arguments; args = arguments as unknown as unknown[];
timestamp = Date.now(); timestamp = Date.now();
const callNow = immediate && !timeout; const callNow = immediate && !timeout;
if (!timeout) timeout = setTimeout(later, waitMs); if (!timeout) timeout = setTimeout(later, waitMs);
if (callNow) { if (callNow) {
result = func.apply(context, args); result = func.apply(context, args || []);
context = args = null; context = args = null;
} }
@ -53,7 +57,7 @@ function debounce(func, waitMs, immediate = false) {
debounced.flush = function() { debounced.flush = function() {
if (timeout) { if (timeout) {
result = func.apply(context, args); result = func.apply(context, args || []);
context = args = null; context = args = null;
clearTimeout(timeout); clearTimeout(timeout);