我无法理解这个?
为什么是我的:
.每个循环都会直接运行,即使我在每个循环中拖延了 1000 毫秒?
问题是 window.location.href 命令在 setTimeout 完成之前运行TO EARLY? stopload() 函数也是如此,它也提前结束了?我看到了一些关于递归 setTimeout 函数的内容,那就是这里需要什么以及如何实现它?
function shop(clickedButton)
{
var buttonvalue = $(clickedButton).val();
startLoad();
pdel = 1000;
$("input:submit[value='buy']").each(function(index)
{
if(index != 1)
{
$("#backgroundPopup").text(index);
var submithing = this;
setTimeout(function(){ clicksubmitbutton(submithing); },pdel);
pdel += 1000;
}
});
stopLoad();
if(buttonvalue == "1")
{
window.scrollTo(0,0);
}
else
{
window.location.href = 'http://my.url';
}
}
最佳答案
Javascript 没有 sleep 或停止的概念。 setTimeout
调用后继续执行。该函数只是安排一个函数在给定的毫秒数后运行。
为了获得您想要的行为,您需要在 setTimeout
回调函数中调用下一次迭代。
类似于:
function submitTheThing(index) {
if (done) { //some logic
return;
}
// do something
setTimeout(function() { submitTheThing(index+1); }, 1000);
}
关于javascript - 在函数结束之前阻止 JS 代码运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15753782/