简体   繁体   English

settimeout javascript无法正常运行?

[英]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 1 2 3 4

but this code shows, 但是这段代码显示

1 4 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 正在编辑同一元素,因此您只能看到上一次操作的结果:4


The setTimeout() method calls a function or evaluates an expression after a specified number of milliseconds. setTimeout()方法将在指定的毫秒数后调用一个函数或对一个表达式求值。 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. setTimeout不会从上一个setTimeout的结束算起时间,而是从setTimeout语句执行的时间算起。

So, all the setTimeout statements with 2 , 3 and 4 are beginning to wait 4 seconds almost at the same time. 因此,所有setTimeout与报表234都开始等待4秒几乎在同一时间。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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