0

I have some JS functions that are supposed to, essentially, display a number on a webpage every 5 seconds. In reality, what happens is that one number is displayed on screen, but it is not updated after 5 seconds (or ever, actually); it simply stays there forever. Curiously, if I add debug points (via Chrome developer tools), the loop works and the number on the screen is updated as expected.

There just seems to be an issue with the loop executing as it should in regular mode (i.e. not in debug mode).

For reference, I have tested in both Safari and Chrome and the issue is the same.

function displayNumbers(){
    document.getElementById("instructions").innerHTML = "";
    document.getElementById("welcome-message").innerHTML = "";

    var numbersCalled = [];
    for (var j=0; j< 90; j++){
        var numberToDisplay = Math.floor(Math.random() * 91) + 1; 
        if (!numbersCalled.includes(numberToDisplay)){
            setTimeout(printNumberToScreen(numberToDisplay), 5000); 
            numbersCalled.push(numberToDisplay);                  
        }
    }
}

function printNumberToScreen(numberToDisplay){
    document.getElementById("number-display").innerHTML = numberToDisplay;
}

'number-display' is initialised as:

<h2 id="number-display"></h2> 
amm
  • 43
  • 1
  • 1
  • 7
  • 2
    That's not how you use [setTimeout](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout). – Teemu Nov 10 '19 at 19:59
  • 2
    Your loop sets 90 timeouts to run at the same time: about 5 second from "now". You have to set each timeout after the previous one has run, or add 5 seconds more to each timeout. – RobG Nov 10 '19 at 20:05
  • And after you've resolved the timeout issue, there's [a closure problem](http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example). – Teemu Nov 10 '19 at 20:06
  • You are invoking printNumberToScreen(numberToDisplay) immediately, not after 5 seconds. – MikNiller Nov 10 '19 at 20:06

1 Answers1

0

You are using setTimeout the wrong way setTimeout accepts callback/anonymous function as first value But you were passing a value returned by printNumberToScreen.

You should pass the function like this setTimeout(printNumberToScreen, 3000)

If you would like to pass argument to printNumberToScreen Then pass anonymous function to setTimeout

E.g setTimeout (() => printNumberToScreen(5), 4000)

myckhel
  • 800
  • 3
  • 15
  • 29