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

3
  • 3
    @FailedUnitTest: No, code in JavaScript runs synchronously unless otherwise stated. Promise callbacks and setTimeout callbacks are both the kinds of "otherwise stated" things. Jun 16, 2017 at 16:39
  • Yes, you are right. I was thinking of ajax calls for some reason. Jun 16, 2017 at 16:40
  • You will probably need to use flags around your prompt, similar to in this question: stackoverflow.com/questions/4122268/… Jun 16, 2017 at 16:42

2 Answers 2

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>

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.