【问题标题】:Javascript code not running sequentiallyJavascript代码未按顺序运行
【发布时间】:2017-06-16 16:35:28
【问题描述】:

Halcyon 在这里帮助处理了循环 - 但有什么方法可以阻止后续代码运行,直到循环结束:

当我运行下面的代码时,我会在 scrollDown 函数运行之前收到输入我的姓名的提示 - 但输入提示是在 scrollDown 代码之后:

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");

任何建议将不胜感激。

谢谢,马克

【问题讨论】:

  • @FailedUnitTest:不,JavaScript 中的代码同步运行,除非另有说明。 Promise 回调和setTimeout 回调都是“另有说明”的东西。
  • 是的,你是对的。出于某种原因,我在考虑 ajax 调用。
  • 您可能需要在提示符周围使用标志,类似于以下问题:stackoverflow.com/questions/4122268/…

标签: javascript


【解决方案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>

【讨论】:

    【解决方案2】:
    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);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-05-30
      • 1970-01-01
      • 2023-03-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多