Halcyon在这里帮助了循环 - 但是有没有办法阻止后续代码运行,直到循环结束:
当我运行下面的代码时,在scrollDown函数运行之前我得到输入我的名字的提示 - 但输入提示符为scrollDown代码之后:
HorizontalOffset

任何建议都将受到赞赏。
谢谢,Mark
答案 0 :(得分:1)
将代码放在最后一次滚动迭代后运行的回调中。
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>
答案 1 :(得分:0)
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);