문제

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.

도움이 되었습니까?

해결책

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.

다른 팁

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top