Created
November 6, 2024 12:08
-
-
Save thekarel/84354d1a34f65c7ba38407092a9049d6 to your computer and use it in GitHub Desktop.
svelte input debounce
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Debounce the input value change event | |
* | |
* Copied from https://github.com/svelte-seoul/svelte-debounce/blob/master/index.js and added types | |
* | |
* Example: run console.log after 750ms of the last input event, no matter how many input events are fired | |
* | |
* ```svelte | |
* <input use:debounce={{callback: console.log}} /> | |
* ``` | |
*/ | |
const debounce = (node: HTMLElement, config: {callback: (v: string) => void; delay?: number}) => { | |
const {callback, delay = 750} = config | |
let timer: number | |
const handleChange = (e: Event) => { | |
const target = e.target as HTMLInputElement | |
const {value} = target | |
clearTimeout(timer) | |
timer = window.setTimeout(() => { | |
callback(value) | |
}, delay) | |
} | |
node.addEventListener('input', handleChange) | |
return { | |
destroy() { | |
node.removeEventListener('input', handleChange) | |
}, | |
} | |
} | |
export {debounce} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment