简体   繁体   English

HTML Javascript-setInterval无法正常运行

[英]HTML Javascript - setInterval is not running properly

I am attaching my code below here for the use of setInterval() function of Javascript. 我将以下代码附加到此处,以使用Java语言的setInterval()函数。 The code runs only one time afer that it is not running docoment.write to write the value of i in the browser. 在未运行docoment.write之后,该代码仅运行一次,以在浏览器中写入i的值。 Could anyone pls let me know at which place I am wrong with my code : 任何人都可以让我知道我的代码在哪里出错:

<html>
<head>
    <script type="text/javascript">
    function inCreas(){
        var i = 0;
        var interval = setInterval(func,2000);
        function func(){i++;
            document.write("<p>This is the value of i : "+ i +"</p>");
            }
    }
    </script>
    </head>
    <body onload="inCreas()">

    </body>
    </html>

I have tried it in IE 8 and Firefox 24.0, but result is same. 我已经在IE 8和Firefox 24.0中尝试过,但是结果是相同的。

Thanks in advance. 提前致谢。 Vasudev 瓦苏杰夫

document.write works only as long as the document is "open". document.write仅在文档处于“打开”状态时有效。 It get's closed when the end html tag is reached. 到达结束html标签后,它将关闭。 After that, calling document.write opens an entirely new document. 之后,调用document.write将打开一个全新的文档。

Now this happens in your page: 现在,这发生在您的页面中:

  1. The original document is created and the onload function is registered. 创建原始文档并注册onload功能。
  2. the document is closed 文件已关闭
  3. the setInterval function triggers setInterval函数触发器
  4. Because the existing document is already closed, a new one is created, completely overwriting the old one. 由于现有文档已经关闭,因此将创建一个新文档,完全覆盖旧文档。 You can test this by putting some stuff inside the body tag - it will disappear as soon as the document.write is executed. 您可以通过在body标签内放置一些东西来进行测试-一旦执行document.write ,它将消失。 This creates an entirely new context - your setInterval is also not present any more in the new document. 这将创建一个全新的上下文-您的setInterval也不再出现在新文档中。

To achieve the effect you want, you could use innerHTML instead - see the DEMO . 要获得所需的效果,可以改用innerHTML参见DEMO

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

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