在 Javascript 中的 while 循环内创建暂停 [英] Create a pause inside a while loop in Javascript
问题描述
我想在 while
循环中创建一个暂停,这样我就可以创建 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.
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.
谷歌搜索setTimeout 循环";准确地告诉您您需要知道的内容.如果你环顾四周,它甚至提到了 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;
// setTimeout approach
function animation_loop() {
someAnimation();
setTimeout(function() {
i++;
if (i < n) {
animation_loop();
}
}, 3000);
};
animation_loop();
// setInterval approach
i = 0;
someAnimation();
iid = setInterval(function() {
i++;
if (i < n) {
someAnimation();
} else {
clearInterval(iid);
}
}, 3000);
这篇关于在 Javascript 中的 while 循环内创建暂停的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!