vasudev mukherjee
vasudev mukherjee

Reputation: 11

HTML Javascript - setInterval is not running properly

I am attaching my code below here for the use of setInterval() function of Javascript. The code runs only one time afer that it is not running docoment.write to write the value of i in the browser. 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.

Thanks in advance. Vasudev

Upvotes: 0

Views: 50

Answers (1)

Christoph
Christoph

Reputation: 51261

document.write works only as long as the document is "open". It get's closed when the end html tag is reached. After that, calling document.write opens an entirely new document.

Now this happens in your page:

  1. The original document is created and the onload function is registered.
  2. the document is closed
  3. the setInterval function triggers
  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. This creates an entirely new context - your setInterval is also not present any more in the new document.

To achieve the effect you want, you could use innerHTML instead - see the DEMO.

Upvotes: 1

Related Questions