Answer the question
In order to leave comments, you need to log in
VUE: How can I change the value in data with a delay of one second while iterating over an array of data?
Good afternoon!
Can you please tell me how to implement the following functionality?
I have an array of values myList and an auxiliary value step in data.
data() {
return {
myList: [1, 2, 1, 3, 4],
step: 0,
};
},
methods: {
onStart() {
this.myList.forEach((item) => {
setTimeout(() => {
this.step = item;
}, 1000);
});
},
}
Answer the question
In order to leave comments, you need to log in
You don't understand how setTimeout works. This function does not stop code execution, but creates a timer in a separate thread, which, after a specified time, will put the callback function call into the JS execution queue. As a result, you almost simultaneously create all the timers, and they fire at the same time.
For cyclic things, either a recursive call to setTimeout or, much better, setInterval is used.
onStart() {
let idx = 0;
const timer = setInterval(
() => {
this.step = this.myList[idx];
idx += 1;
if (idx >= this.myList.length) {
clearInterval(timer);
}
},
1000,
);
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question