Link to home
Start Free TrialLog in
Avatar of MBarongan
MBaronganFlag for United States of America

asked on

setInterval() and setTimeout don't work with document.write

Is there a way to make setInterval() and setTimeout() call document.write repeatedly? It seems like document.write isn't supported by setInverval and setTimeout.

For example, these scripts don't work:

function loopFun() {
  document.write("Here we go again...<br/>");
   setTimeout("loopFun()", 5000);
   }
loopFun();

function loopFun() {
  document.write("Here we go again...<br/>");
     setInterval("loopFun()", 5000);
}
loopFun();

But if you replace document.write() with alert(), the scripts work:

function loopFun(){
alert("Here we go again");
setTimeout("loopFun()", 5000);
}
loopFun();

function loopFun(){
alert("Here we go again");
setInterval("loopFun()", 5000);
}
loopFun();
Avatar of Dave Baldwin
Dave Baldwin
Flag of United States of America image

This page from W3Schools shows different ways to use those functions: http://www.w3schools.com/js/js_timing.asp
Avatar of MBarongan

ASKER

I looked through all the examples from http://www.w3schools.com/js/js_timing.asp, but I don't see document.write in any of them (unless I overlooked it). Does that mean document.write can't be used with setInterval and setTimeout?
I didn't have any problem getting 'document.write' to work twice... but the timing loop failed after the second time.  Note that the function with 'document.write' must be in the body of the page.  'alert' will work in the <head> section but 'document.write' will not.

Try the examples on that page and see if they work for you as they are.  Note that setTimeout is shown as working once while setInterval is shown as being repetitive.  I suspect that your 'setInterval' isn't going to work right because you're setting a repetitive interval over and over again without ever shutting any of the intervals down.
In layman's terms, what do you want to make happen?  document.write() is kind of "hamfisted."  Have you tried putting the interval timers outside of the function definition?
ASKER CERTIFIED SOLUTION
Avatar of leakim971
leakim971
Flag of Guadeloupe image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Using the <div> tag made it work right. Thank you for clarifying the correct usage of document.write().