mirror of
https://github.com/CharaChorder/DeviceManager.git
synced 2026-02-23 01:22:03 +00:00
[#167] Expand textarea for sentence input; use untrack to break recursive reactivity loops hanging the page on long sentences; Use better error message instead of ERROR (#182)
This commit is contained in:
committed by
GitHub
parent
7f27499003
commit
0e5640a1ee
46
src/lib/util/debounce.ts
Normal file
46
src/lib/util/debounce.ts
Normal file
@@ -0,0 +1,46 @@
|
||||
/**
|
||||
* Creates a debounced function that delays invoking the provided function
|
||||
* until after 'wait' milliseconds have elapsed since the last time it was
|
||||
* invoked.
|
||||
*
|
||||
* I could use _.debounce(), but bringing dependency on lodash didn't feel
|
||||
* justified yet.
|
||||
*
|
||||
* @param func The function to debounce
|
||||
* @param wait The number of milliseconds to delay execution
|
||||
* @returns A debounced version of the provided function
|
||||
*/
|
||||
function debounce<T extends (...args: any[]) => void>(
|
||||
func: T,
|
||||
wait: number
|
||||
): T & { cancel: () => void } {
|
||||
let timeout: ReturnType<typeof setTimeout> | null = null;
|
||||
|
||||
const debounced = function(
|
||||
this: ThisParameterType<T>, ...args: Parameters<T>
|
||||
): void {
|
||||
const context = this;
|
||||
|
||||
const later = function() {
|
||||
timeout = null;
|
||||
func.apply(context, args);
|
||||
};
|
||||
|
||||
if (timeout) {
|
||||
clearTimeout(timeout);
|
||||
}
|
||||
|
||||
timeout = setTimeout(later, wait);
|
||||
};
|
||||
|
||||
debounced.cancel = function() {
|
||||
if (timeout) {
|
||||
clearTimeout(timeout);
|
||||
timeout = null;
|
||||
}
|
||||
};
|
||||
|
||||
return debounced as T & { cancel: () => void };
|
||||
}
|
||||
|
||||
export default debounce;
|
||||
Reference in New Issue
Block a user