我对 Vue 还很陌生。这让我很困惑。
如果我在方法内部有这个 while 循环。
methods: {
test: function() {
counter = 0;
while( counter < 10 ){
console.log( counter );
counter++;
window.setTimeout( function() {
console.log( 'Test' );
}, 1000)
}
}
},
mounted() {
this.test();
}
然后在我的控制台中,它将打印以下内容:
0
1
2
3
4
5
6
7
8
9
(10) Test
如果我错了请纠正我,但不应该这样写:
0
Test
1
Test
2
Test
3
Test
4
Test
5
Test
6
Test
7
Test
8
Test
9
Test
...中间有几秒钟的延迟吗?
我问这个问题的原因是我正在从 API 中提取数据,并且只想在填充数据后初始化一个函数。
This post ,建议对 setTimeout 使用箭头函数,但我在执行此操作时没有看到任何差异。
我已经看了很多 Vue's lifecycle ,但这也没有告诉我答案。
最佳答案
while 循环中的计数速度非常快(< 1 秒),因此当超时执行时,while 循环的其余部分已经执行(打印 0 到 9),之后超时达到倒计时并打印连续‘测试’。这会导致它依次打印 10 次,在控制台中以前缀 (10) 缩写,而不是按字面打印 test 10 次。
发生这种情况是因为当您调用 window.setTimeout
时,此处调用的代码将在 x 毫秒后并行执行,因此其余代码会继续处理,而超时正在倒计时。
如果您想要预期的结果,您应该直接执行它而不是使用超时:
methods: {
test: function() {
counter = 0;
while( counter < 10 ){
console.log( counter );
counter++;
console.log( 'Test' );
}
}
},
mounted() {
this.test();
}
如果你想在每个数字之间等待 1 秒,你应该使用递归函数,如下所示:
test(0);
function test (counter) {
if (counter < 10) {
console.log( counter );
counter++;
console.log( 'Test' );
window.setTimeout( function() {
test(counter);
}, 1000)
}
}
确保为此使用初始值或默认值 0
关于javascript - 使用 setTimeout 了解 Vue 中的 while 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53317581/