2

Halcyon helped with the loop here - but is there any way to stop the subsequent code from running, until after the loop has finished:

When I run the code below, I get the prompt for entering my name, before the scrollDown function runs - but the input prompt as AFTER the scrollDown code:

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

Any advice would be appreciated.

Thanks, Mark

Barmar
  • 741,623
  • 53
  • 500
  • 612
Mark Tait
  • 545
  • 3
  • 12
  • 22
  • 3
    @FailedUnitTest: No, code in JavaScript runs **synchronously** unless otherwise stated. Promise callbacks and `setTimeout` callbacks are both the kinds of "otherwise stated" things. – T.J. Crowder Jun 16 '17 at 16:39
  • Yes, you are right. I was thinking of ajax calls for some reason. – FailedUnitTest Jun 16 '17 at 16:40
  • You will probably need to use flags around your prompt, similar to in this question: https://stackoverflow.com/questions/4122268/using-settimeout-synchronously-in-javascript – scrappedcola Jun 16 '17 at 16:42

2 Answers2

1

Put the code in a callback that you run after the last scroll iteration.

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>
Barmar
  • 741,623
  • 53
  • 500
  • 612
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);
yqlim
  • 6,898
  • 3
  • 19
  • 43