1

So how do I make it wait 1000 milliseconds until it executes a different code(btw, What is the JavaScript version of sleep()? IS NOT helping me, so PLEASE don't close this question(and I'm not very good with JavaScript)).
Here is my code:

<!DOCTYPE html>
<html>
<head>
<title>Start</title>
</head>
<body>
<div id="changeText" style="font-family:verdana;"><br><br>
Press ENTER to continue</div>

<script>
document.addEventListener('keydown',function(e){
    if(e.keyCode==13){ 
        newPageTitle = 'Executing...';
        document.title = newPageTitle;
        //wait goes here
        newPageTitle = 'Loading...';
        document.title = newPageTitle;
        //wait goes here
        newPageTitle = 'Fetching Data...';
        document.title = newPageTitle;
        //wait goes here
        newPageTitle = 'Done!';
        document.title = newPageTitle;
        //wait goes here
        window.location.href=('https://example.com');
        
}
});
</script>
<script>
var text = ["<br><br>Press ENTER to continue_", "<br><br>Press ENTER to continue"];
var counter = 0;
var elem = document.getElementById("changeText");
var inst = setInterval(change, 700);

function change() {
  elem.innerHTML = text[counter];
  counter++;
  if (counter >= text.length) {
    counter = 0;
  }
}
</script>
</body>
</html>
what I want it to do is whenever you press enter it changes the title, then it waits 1000 milliseconds to change the tile again, and then it waits 680 milliseconds to redirect you to another webpage (also for some reason when it's in the code snippet you have to click the snippet area and the you can press enter).
  • 2
    You are looking for [`setTimeout`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout). – Wais Kamal Jul 02 '21 at 21:32
  • 1
    There is nothing in JavaScript that's truly equivalent to sleep. You either have to learn how async/await works (which I can't explain in a short answer), which can fake having a sleep() function, or use a bunch of nested `setTimeout`s. – kshetline Jul 02 '21 at 21:33
  • I know you've seen [What is the JavaScript version of sleep()?](https://stackoverflow.com/questions/951021/what-is-the-javascript-version-of-sleep) and you don't think it answers your question, but it does. Use `async`/`await` and plop their `sleep` function in your code and you'll see it works. It is _the_ way to do it and any answers in this thread are going to essentially do exactly that. Sure, you could use raw `setTimeout`s, but `sleep` is simply a promisifed timeout, which just makes it easier to use than callbacks. – ggorlen Jul 02 '21 at 21:57
  • umm... could you include an example for that? –  Jul 02 '21 at 22:06
  • also I tried to use raw `setTimeouts` but I don't think it worked or I just did something wrong –  Jul 02 '21 at 22:09
  • See the code in the link. The example you accepted basically just smushes some extra nonessential functionality specific to your use case into the `sleep` provided in the link and renames it to `wait`. It's better to keep `sleep` generic as a utility/library function, then add your own custom function between the sleep calls. – ggorlen Jul 02 '21 at 22:25

1 Answers1

0

To do your animation on the document title, that would be a serie of nested setTimeout() function looking like this:

setTimeout(function () {
  document.title = "Executing...";
  setTimeout(function () {
    document.title = "Loading...";
    setTimeout(function () {
      document.title = "Fetching Data...";
      setTimeout(function () {
        document.title = "Done!";
        setTimeout(function () {
          window.location.href = "https://example.com";
        }, 1000);
      }, 4000);
    }, 3000);
  }, 2000);
}, 1000);

I agree that is ugly. And you would have to calculate the added delays from outer to inner... So you could have a function to set the timeouts and make your code readable and maintainable.

Notice that nice looking script:

wait(1000, 'Executing...')
wait(2000, 'Loading...')
wait(3000, 'Fetching Data...')
wait(4000, 'Done!')
wait(1000)

Here is a demo where I console logged the title texts... Because we won't see the effect otherwize, since the snippet is an iframe.

document.addEventListener('keydown', function(e) {
  if (e.keyCode == 13) {
    wait(1000, 'Executing...')
    wait(2000, 'Loading...')
    wait(3000, 'Fetching Data...')
    wait(4000, 'Done!')
    wait(1000)
  }
});

var text = ["<br><br>Press ENTER to continue_", "<br><br>Press ENTER to continue"];
var counter = 0;
var elem = document.getElementById("changeText");
var inst = setInterval(change, 700);

function change() {
  elem.innerHTML = text[counter];
  counter++;
  if (counter >= text.length) {
    counter = 0;
  }
}

// A global variable to sum up the delays
let wait_time = 0;

function wait(delay, message) {

  // Each "wait" call is adding its delay to the global wait_time
  wait_time += delay

  // This is the delay to use in this timeout
  // "let" making it scoped to this function call
  let timeoutDelay = wait_time;
  console.log(timeoutDelay)

  // Set a timeout
  setTimeout(function() {

    // If there is a message, use it on the title.
    // else, redirect
    if (message) {
      console.log(message)
      document.title = message;
    } else {
      window.location.href = ('https://example.com');
    }
  }, timeoutDelay)
}
<div id="changeText" style="font-family:verdana;"><br><br> Press ENTER to continue</div>
Louys Patrice Bessette
  • 33,375
  • 6
  • 36
  • 64