我试图从循环内调用函数,当函数完成执行时,循环继续到下一次迭代并再次调用它。但循环不会等待函数完成,而是调用该函数的 4 个实例并同时运行它们!我应该将整个函数放入循环中还是让循环等待函数执行?谢谢
for (var i=2; i<=4; i++){
galleryAnimation(i); //This is executed 3 times at once
}
function galleryAnimation(i){
$("#pic" + i).delay(delayTime).fadeIn(duration);
}
函数按照您的要求执行了3次,问题是delay和fadeIn都使用计时器:它们在将来函数执行时设置一个计时器并立即返回:它们是非阻塞调用。因此,在您的情况下,因为您在 0.0001s、0.0002s 和 0.0003s 处调用该函数 3 次,所以这三个时间点在 5.0001、5.0002 和 5.0003 处开始。
您的想法是“阻止调用”这些函数。您希望整个执行停止,直到动画完成。这将在持续时间内停止整个浏览器 Javascript 引擎,这意味着不可能有其他动画或用户 javascript 交互。 要解决这个问题,你
必须使用回调。您可以为 fadeIn 提供一个函数,动画完成后将调用该函数:
http://api.jquery.com/fadeIn/ 回调.delay()var i, factor,
duration = 250,
delayTime = 500;
for (i = 2, factor = 0; i <= 4; i++, factor++) {
galleryAnimation(i, factor);
}
function galleryAnimation(i, factor) {
$("#pic" + i).delay(factor * delayTime).fadeIn(duration);
}
这与您的方法的运行方式相同,只是延迟每次都会变长。
通用解决方案 1 - 使用
setInterval()
来让您的工作函数(执行
fadeIn
的函数)按预定义的时间间隔调用:var elements = $("#pic2,#pic3,#pic4").toArray(), // or any other way to select your elements
duration = 250,
delayTime = 500,
intervalId = setInterval(function () {
$(elements.shift()).fadeIn(duration);
if (elements.length === 0) {
clearInterval(intervalId);
}
}, delayTime);
通用解决方案 2 - 使用上一个动画完成时调用的回调:
var elements = $("#pic2,#pic3,#pic4").toArray(), // or any other way to select your elements
duration = 250,
delayTime = 500,
next = function () {
$(elements.shift()).delay(delayTime).fadeIn(duration, next);
};
next(); // start the chain
function galleryAnimation(i, iBool){
$("#pic" + i).delay(delayTime).fadeIn(duration);
iBool = 0;
}
然后返回;
for (var i=2; i<=4; i++){
galleryAnimation(i, iBool);
// If iBool = 0 then continue
// Else Break
}
这可能是一个解决方案,因为循环需要返回值来确定下一步,继续或中断。
function fadeInAnimation(index){
$("#pic" + index).delay(delayTime).fadeIn(duration, function(){
photoIndex();
});
}
function photoIndex(){
index++;
fadeInAnimation(index);
}
fadeInAnimation(index);
});
我意识到使用循环对于这样的事情来说是一个非常糟糕的主意。这段代码将允许我添加任意数量的图像,只需在文件夹中重命名它们,而不是手动将它们编码为每张照片的回调。 感谢那些回答的人。您的建议非常棒,并且一定会在其他应用程序(例如此应用程序)中记住它们
function plus(x){
return x + 1
}
let number;
let sum = 0;
for (let count = 1; count <= 3; plus(count)) {
number = Number(prompt("enter the number: " , 1));
sum += number;
}
console.log(sum);