Skip to content

Instantly share code, notes, and snippets.

@danielkellyio
Created October 29, 2024 19:37
Show Gist options
  • Save danielkellyio/a31742358a1b7349accdc414bba2dbf0 to your computer and use it in GitHub Desktop.
Save danielkellyio/a31742358a1b7349accdc414bba2dbf0 to your computer and use it in GitHub Desktop.
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