-2

I want to make a timer using while, and when I lunch the code in Chrome, the Chrome don't load.

I am making this:

var time = 0;

        while (time < 5) {
            setTimeout(function(){
                tempo[0].innerHTML = time;
                time++;
            }, 1000);
        }

I expect when time it gets to 5, javascript will exit the loop and execute the next action

Samtapes
  • 194
  • 1
  • 3
  • 8
  • The `setTimeout()` out function schedules a function to be called at some time in the future, but it returns **immediately**. – Pointy May 12 '19 at 20:44
  • The callback first passed to `setTimeout` will be called after the `while` loop will be finished. – Maheer Ali May 12 '19 at 20:44

1 Answers1

1

You should use async and await

var time = 0;
var result = document.querySelector('#display')
async function start(){
  while (time < 5) {
   await new Promise(res => {
     setTimeout(function(){
      result.innerHTML = time;
      time++;
      res();
    }, 1000);
   }) 
  }
}
start()
<div id="display"></div>
Maheer Ali
  • 35,834
  • 5
  • 42
  • 73