i have a file which is executing javascript.I want it to load after some time.For eg- my script is <script>document.write("hello")</script> and it is loading directly when i am opening the file i want it to come after some time approx 5sec. Can you help me out as i am beginner in Javascript.Please help me to do this.Thanks in advance
3 Answers
You can use setTimeout function like this:
setTimeout(function() {
// Do something after 5 seconds
}, 5000);
and one thing that @mplungjan mentioned in comments that when document.write executes it wipes the document and all scripts will be removed so you should not use document.write, instead of that use some alternate way as @mplungjan posted.
6 Comments
You cannot document.write after the page has loaded. If you do, the page is wiped.
It is quite easy to change the script to execute later. For example wrap the contents in a function and change any document.write inside it (show us the code please) to string concatenations
function concatIt() {
var text = "";
text += "some string previously written with document.write";
text += "some string previously written with document.write";
text += "some string previously written with document.write";
return text; // send text to calling statement
}
window.onload=function() { // when page has loaded
setTimeout(function() {
document.getElementById("somecontainer").innerHTML=concatIt();
},10000); // insert after 10 seconds
}
Comments
You can use -
setTimeout(function() {
document.getElementsByTagName('body')[0].appendChild('<script>document.write("hello")</script>');
}, 5000);
Based on comments-
As a suggestion, you should not be adding such a script after the document loads. This is because if you use 'document.write('something')', it will remove the previous content in the document and just write 'something' into it.
document.createElement()