Function
debounce
(
fn: (...args: T) => U,
time: number,
)
Source from the content-addressed store, hash-verified
| 64 | } |
| 65 | |
| 66 | export function debounce<T extends unknown[], U>( |
| 67 | fn: (...args: T) => U, |
| 68 | time: number, |
| 69 | ) { |
| 70 | const state: { |
| 71 | timer: number; |
| 72 | result?: U; |
| 73 | args?: T; |
| 74 | } = { |
| 75 | timer: 0, |
| 76 | }; |
| 77 | function reset() { |
| 78 | if (state.timer) { |
| 79 | window.clearTimeout(state.timer); |
| 80 | state.timer = 0; |
| 81 | } |
| 82 | } |
| 83 | function run() { |
| 84 | reset(); |
| 85 | if (state.args) state.result = fn(...state.args); |
| 86 | } |
| 87 | return function debounced(...args: T) { |
| 88 | reset(); |
| 89 | state.args = args; |
| 90 | state.timer = window.setTimeout(run, time); |
| 91 | return state.result; |
| 92 | }; |
| 93 | } |
Tested by
no test coverage detected