在javascript中在while循环内创建一个暂停 [英] Create a pause inside a while loop in javascript
问题描述
我想在中创建一个暂停,同时
循环,这样我就可以创建每个出现的 n
动画另一个3秒后。
I would like to create a pause inside a while
loop so that I can create n
animations that each appear 3 seconds after the other.
我尝试了以下内容,但它不起作用。很想有人告诉我我做错了什么。谢谢!!
I've tried the following, but it doesn't work. Would love to have someone show me what I'm doing wrong. Thanks!!
i=0;
while (i < n) {
someanimation();
setTimeout(function(){
i++;
}, 3000);
};
推荐答案
setTimeout
不停顿;它要求Javascript稍后运行其他代码。
setTimeout
does not pause; it asks Javascript to run some other code later.
Google搜索setTimeout loop会告诉您确切需要了解的内容。如果你环顾一下,它甚至提到了setInterval。区别:使用setTimeout循环将在循环之间等待3秒,而setInterval将使循环总共花费3秒(包括动画花费的时间,只要它少于3秒:))。此外,setInterval构造一个无限循环,您必须在所需的次数之后突破该循环; setTimeout要求你自己构造循环。
Googling for "setTimeout loop" tells you exactly what you need to know. If you look around a little bit, it even mentions setInterval. The difference: using setTimeout to loop will wait 3 seconds in between loops, whereas setInterval will make it take 3 seconds total for the loop (including however much time the animation takes, as long as it's less than 3 seconds :) ). Also, setInterval constructs an infinite loop that you'll have to break out of after the desired number of times; setTimeout requires you to construct the loop yourself.
i = 0;
function animation_loop() {
someAnimation();
setTimeout(function() {
i++;
if (i < n) {
animation_loop();
}
}, 3000);
};
animation_loop();
i = 0;
someAnimation();
setInterval(function() {
i++;
if (i < n) {
someAnimation();
}
}, 3000);
这篇关于在javascript中在while循环内创建一个暂停的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!