debounce

See throttle if you want your function to run at the start of the N seconds.

typescriptjavascript
const debounce = <T extends CallableFunction>(fn: T, delay: number): T => {
let timer: ReturnType<typeof setTimeout>
return ((...args: any[]) => {
if (timer) clearTimeout(timer)
timer = setTimeout(() => {
fn(...args)
}, delay)
}) as any
}
Created 03/28/21 • Updated 03/28/21
Found a mistake, or want to suggest an improvement? Edit on GitHub here
and see edit history here

License & Attribution

Attribution

You should place the following attribution (and probably the license below it) above your copy of the code, but 🤷‍♂️.

This snippet "debounce" from "https://soorria.com/snippets/debounce" 
was created by Soorria Saruva (https://soorria.com) and is covered under the 
MIT license found here: https://github.com/soorria/soorria.com/blob/master/LICENSE.

License

If you want, you can (and probably should) include the entire license below. I'm not a lawyer, though so idrk.

MIT License Copyright (c) 2022 Soorria Saruva

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice (including the next paragraph) shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.