Replies: 1 comment 2 replies
-
You (appear to) want "when changed, or no changes for x seconds." Effectively, a watch with a timeout. That code watches for a change and calls the function 3 seconds later, clearing any previous timeout; effectively, it's a debounced watch: it will only call the function after a change if there have been no more changes in 3 seconds. That (with a max wait, as well) is available in the form of I assume you would want to keep triggering after successive timeouts. I.e., trigger every x seconds, or sooner if there is a change. Because of the way the callback is being called, I've made it so that a watch-triggered call has the standard arguments and a timeout-triggered call has the value of the source passed as the first two, and a no-op import {
watch,
type Ref,
type WatchOptions,
} from "vue";
function watchWithPeriod<T>(
ref: Ref<T>,
cb: (
value: T,
oldValue: T | undefined,
onCleanup: (cleanupFn: () => void) => void,
) => void,
options: WatchOptions & { period: number },
) {
let timer: number | undefined = setInterval(
() => cb(ref.value, ref.value, () => {}),
options.period,
);
watch(
ref,
(...args) => {
clearTimeout(timer);
timer = setInterval(
() => cb(ref.value, ref.value, () => {}),
options.period,
);
cb(...args);
},
options,
);
} It would be used like this: import { ref } from "vue";
const msg = ref("");
watchWithPeriod(
msg,
(value, oldValue, onCleanup) => {
if (value !== oldValue)
console.log("Value changed:", `"${oldValue}"`, `"${value}"`);
else
console.log("Interval:", `"${value}"`)
onCleanup(() => console.log("Cleanup called."));
},
{ period: 3000 },
); |
Beta Was this translation helpful? Give feedback.
-
Hi all,
I have a usecase where I want to trigger a method when something is added to my ref, or the ref didn't change for x seconds. I asked ChatGPT for a suggestion:
https://chat.openai.com/share/b781d99c-26d2-4cc4-a8dd-f0d7ed88e555
I have been looking through the vueuse list, and cant find any utility method which does something like this. Would it be useful to add this to vueuse, or not?
Beta Was this translation helpful? Give feedback.
All reactions