I need to stop watch() but the docs don't really explain how to do that.
This watcher runs until the loop is finished (1000 seconds):
const state = reactive({
val: 0
})
watch(() => state.val, () => {
console.log(state.val)
})
for (let i = 1; i < 1000; i++) {
setTimeout(function timer() {
state.val = state.val + 1
}, i * 1000);
}
How do I stop the watcher after running once? Using watchEffect is not an option because for my use case the watcher needs to run several times before stopped, which is not described in this simplified example. From my understanding watchEffect runs only once (after initiation).
The "watch" function returns a function which stops the watcher when it is called :
const unwatch = watch(someProperty, () => { });
unwatch(); // It will stop watching
To watch a change only once:
const unwatch = watch(someProperty, () => {
// Do what your have to do
unwatch();
});