Question

I am using the following code in order to display some texts to the users.

basically what I need to show is:

1 2 3 4

but this code shows,

1 4

here is the code:

    <script>
    function myFunction() {
    setTimeout(function() {
      document.getElementById('p').innerHTML = "1";
    }, 2000);

    setTimeout(function() {
      document.getElementById('p').innerHTML = "2";
    }, 4000);

    setTimeout(function() {
      document.getElementById('p').innerHTML = "3";
    }, 4000);

    setTimeout(function() {
      document.getElementById('p').innerHTML = "4";
    }, 4000);
    };
    </script>


<p id="p"></p>

<input onclick="myFunction()" type="submit" />

does anyone know why this is happening?

Thanks in advance.

Was it helpful?

Solution

because

setTimeout(function() {
  document.getElementById('p').innerHTML = "2";
}, 4000);

setTimeout(function() {
  document.getElementById('p').innerHTML = "3";
}, 4000);

setTimeout(function() {
  document.getElementById('p').innerHTML = "4";
}, 4000);
};

are editing the same element so you see only the result of the last operation: 4


The setTimeout() method calls a function or evaluates an expression after a specified number of milliseconds. and in your case the time is same, so all executed at same time.

set some interval between them.

OTHER TIPS

setTimeout doesn't calculate time from the finishing of previous setTimeout, but from the time the setTimeout statement was executed.

So, all the setTimeout statements with 2, 3 and 4 are beginning to wait 4 seconds almost at the same time.

You are editing the same element in quick succession, if you set different values for setTimeout, say 1000, 2000, 3000, 4000, you would see the text change from 1 to 2 to 3 to 4, with a 1s interval (roughly) between each change.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top