简体   繁体   中英

settimeout javascript doesn't function properly?

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.

您正在快速连续地编辑相同的元素,如果您为setTimeout设置了不同的值,例如1000、2000、3000、4000,您会看到文本从1更改为2到3更改为4,间隔为1s(大约)每次更改。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM