Reputation: 11
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
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:
setInterval
function triggersdocument.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