Javascript代码不是按顺序运行
问题描述:
太平帮助这里的循环 - 但有没有办法停止运行后续代码,直到循环完成后:Javascript代码不是按顺序运行
当我运行下面的代码,我得到的提示进入我的名,下滚功能运行之前 - 但输入提示的下滚码AFTER:
function scrollDown(num_times) {
num_times -= 1;
if (num_times === 0) {
return;
}
window.scrollBy(0, 500); // horizontal and vertical scroll increments
setTimeout(function() {
scrollDown(num_times);
}, 500);
}
//This should run first and scroll the screen before prompting
scrollDown(30); // scroll down 30 times
//However this prompt comes up before the above code has ran
var kw = prompt("Please enter your name");
任何意见,将不胜感激。
谢谢,马克
答
var kw;
function scrollDown(num_times) {
if (num_times === 0) {
/* you can define your prompt after scrollDown has ended */
kw = prompt("Please enter your name");
return;
}
window.scrollBy(0, 500);
setTimeout(function() {
scrollDown(num_times - 1);
}, 500);
}
scrollDown(30);
答
将代码放在你最后一次滚动迭代后执行的回调。
function scrollDown(num_times, callback) {
if (num_times === 0) {
callback();
}
window.scrollBy(0, 500); // horizontal and vertical scroll increments
setTimeout(function() {
scrollDown(num_times - 1, callback);
}, 500);
}
//This should run first and scroll the screen before prompting
scrollDown(30, function() {
kw = prompt("Please enter your name");
document.getElementById("result").textContent = kw;
}
); // scroll down 30 times
Your name is: <span id="result"></span>
@FailedUnitTest:没有,在JavaScript代码运行** **同步,除非另有说明。 Promise回调函数和'setTimeout'回调函数都是“另外声明”的东西。 –
是的,你是对的。出于某种原因,我正在考虑ajax电话。 – FailedUnitTest
您可能需要在提示符周围使用标志,类似于此问题:https://stackoverflow.com/questions/4122268/using-settimeout-synchronously-in-javascript – scrappedcola