0

I am running a for loop with a break of 1 second between each iteration:

<html>
<body>
<script>

var text = "";
var i;

// Wait function
function wait(ms){
   var start = new Date().getTime();
   var end = start;
   while(end < start + ms) {
     end = new Date().getTime();
  }
}

for (i = 0; i < 5; i++) {
  text += "The number is " + i + "<br>";
  wait(100)
}

</script>

<script>document.write(text)</script>

</body>

Currently, when I open the file in a web browser, the browser window is loading until the for loop has finished and then the results are displayed (five output lines). Is there a way to display the out put "as it happens". With this I mean, I open the page and every second a new line is printed. Thank you!

Stücke
  • 868
  • 3
  • 14
  • 41
  • 5
    All that wait does is freeze the browser. Learn to use setTimeout/setInterval and do not use document.write. – epascarello Jul 16 '19 at 14:40
  • 1
    Generally you would set a timeout inside the for loop using the iterator as a multiplier for the time delay (`i*1000`). Are you trying to completely pause execution, or simply delay the time between writing things to the page? – DBS Jul 16 '19 at 14:44
  • I am trying to delay the time between writing – Stücke Jul 16 '19 at 14:53

3 Answers3

1

You should learn about timeout and interval concepts in Javascript.

Here is code that will do the work. Examine it.

<html>
<body>
<script>

function waitAndWrite(num) {
    setTimeout(() => {
        let text = "The number is " + num + "<br>";
        document.write(text)
    }, num * 1000)
}

for (let i = 0; i < 5; i++) {
    waitAndWrite(i)
}
</script>
</body>
SimoMatavulj
  • 594
  • 3
  • 11
  • Thanks! How can I return the text as a replacement of the previous text line or in other words not add a new line but remove the old one first and then add the new line? – Stücke Jul 16 '19 at 19:19
  • Also, if I run the script on my computer I all lines are displayed at once. – Stücke Jul 16 '19 at 19:20
  • 1
    Do something like this ` ` – SimoMatavulj Jul 16 '19 at 21:00
  • Thanks! And how do I start this and display the results? – Stücke Jul 17 '19 at 15:25
1

What you are trying to achieve manually, you can achieve the same with WindowOrWorkerGlobalScope.setTimeout():

The setTimeout() method of the WindowOrWorkerGlobalScope mixin (and successor to Window.setTimeout()) sets a timer which executes a function or specified piece of code once the timer expires.

for (let i = 0; i < 5; i++) {
  setTimeout(() => document.write("The number is " + i + "<br>"), 1000 * i); // multiply the delay with i in each iteration
}
Mamun
  • 66,969
  • 9
  • 47
  • 59
1

Instead of using your own "wait" function, you could use setInterval(fn, timeout) src instead.

var i = 0;
var interval = setInterval(() => {
  i = i + 1;
  if(i === 5) {
    clearInterval(interval);
  }
  document.write("Your text " + i);
}, 1000);
Sebastian Waldbauer
  • 674
  • 1
  • 10
  • 17