0

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

2
  • 1
    You can't use document.write after the document has finished loading. Select the element you want to add the content to and either create the new DOM node(s) and append them or append the extra HTML string to its innerHTML property. Commented Nov 23, 2013 at 14:46
  • You can't? It does work on Chrome. Commented Nov 23, 2013 at 14:57

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.