Created
October 29, 2024 19:37
-
-
Save danielkellyio/a31742358a1b7349accdc414bba2dbf0 to your computer and use it in GitHub Desktop.
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
import { ref, watch, readonly } from 'vue'; | |
export const useRefDebounced = (aRef, ms) => { | |
const debouncedRef = ref(aRef.value); | |
// use the debounce function defined below to return a debounced ref whose value only syncs with `aRef` after `ms` milliseconds | |
const debouncedUpdate = debounce(() => { | |
debouncedRef.value = aRef.value; | |
}, ms); | |
watch(aRef, debouncedUpdate); | |
return readonly(debouncedRef); | |
}; | |
function debounce(func, delay) { | |
let timeoutId; | |
return function () { | |
const context = this; | |
const args = arguments; | |
clearTimeout(timeoutId); | |
timeoutId = setTimeout(() => { | |
func.apply(context, args); | |
}, delay); | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment