I'm fairly new to Vue and I find this concept really confusing.
Imagine having a while loop inside a method like this:
methods: {
test: function() {
counter = 0;
while( counter < 10 ){
console.log( counter );
counter++;
window.setTimeout( function() {
console.log( 'Test' );
}, 1000)
}
}
},
mounted() {
this.test();
}
When you run it, the output in the console looks like this:
0
1
2
3
4
5
6
7
8
9
(10) Test
But shouldn't the output actually be:
0
Test
1
Test
2
Test
3
Test
4
Test
5
Test
6
Test
7
Test
8
Test
9
Test
... with a one-second delay between each item?
The reason I'm asking is because I need to wait for data from an API before running a function.
One suggestion recommends using arrow functions for setTimeout, but I haven't seen any difference in results.
I've also studied Vue's lifecycle, but didn't find the solution there either.