0

how do I estabilish a wait time of 10 seconds between Loops?

Is it correct?

Here is my code:

<!DOCTYPE html>
<html>
    <head>
       <title>Tableau Zika</title>
    </head>
        <body>
            <script>
var i=3;

do { 

window.open("TESTE" + i + ".HTML","_self");
i++;

setTimeout(alert("4 seconds"),4000);

}
while (i<=5);

</script>

</html>
V. Han
  • 11
  • Duplicate of https://stackoverflow.com/questions/951021/what-is-the-javascript-version-of-sleep – Markus Zeller Nov 23 '18 at 19:23
  • 10 seconds are 10000 ms, not 4000 ms. – Markus Zeller Nov 23 '18 at 19:24
  • this should be opened in HTML format. – V. Han Nov 23 '18 at 19:58
  • Opening a new window with `_self` as the target will cause all the code to start processing from scratch and so any looping you may have been doing and any variables you may have had in memory would all be lost. If you want to replace the contents in the current window, just use `location=...`. – Scott Marcus Nov 23 '18 at 20:02
  • could you give me an example? – V. Han Nov 23 '18 at 20:07
  • If you are just trying to load another page into the current window, just write `location = someURL`, not `window.open()`. But, when you load another document into the current window, the current code stops running and the code from the new window begins, so any JavaScript that was running will stop. – Scott Marcus Nov 23 '18 at 20:11

2 Answers2

1

Don't use a loop at all. Just set your timer to call a callback function at regular intervals.

var counter = 0;

function doWork(){
  if(counter < 5){
    console.log("doing work", counter);
    counter++;
  } else {
    clearInterval(timer);
    console.log("work completed");
  }
}

let timer = setInterval(doWork, 3000);

You can also control the timing such that the timer doesn't begin counting until the main work has finished processing by changing the code to make recursive setTimeout calls:

var counter = 0;
var timer = null;

(function doWork(){
  // Guard against doWork being called from multiple sources
  // and potentially initiating multiple timers.
  clearTimeout(timer);
  
  if(counter < 5){
    console.log("doing work", counter);
    counter++;
    timer = setTimeout(doWork, 3000);
  } else {
    clearTimeout(timer);
    console.log("work completed");
  }
})();
Scott Marcus
  • 57,085
  • 6
  • 34
  • 54
1

You can make an async/await function that pauses during your loop. This will require a modern javascript engine and require you put your logic inside a function which you then call.

const pause = (time) => new Promise(resolve => setTimeout(resolve, time))

async function start(){
    var i=3;

    do { 
      console.log("TESTE" + i + ".HTML")
      i++;
      await pause(1000) // change to 10000 for 10 seconds
    } while (i<=5);
}

start()
Mark
  • 74,559
  • 4
  • 81
  • 117