E
E
Evgeny Silkin2022-03-28 15:29:10
JavaScript
Evgeny Silkin, 2022-03-28 15:29:10

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,
    };
  },


It is necessary that when iterating over values ​​from the array, the value in step changes with a delay. This is necessary so that elements on pages with a certain number light up when their number is assigned to the step value.

My attempt:
methods: {
    onStart() {
      this.myList.forEach((item) => {
        setTimeout(() => {
          this.step = item;
        }, 1000);
      });
    },
}


As a result, the last element burns immediately.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Rsa97, 2022-03-28
@EvgenySilkin

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 question

Ask a Question

731 491 924 answers to any question