setInterval vs. setTimeout in Javascript

Recently i ran into a strange javascript behavior.

I tried to periodically update a certain container on a page.

At first i tried it with:

foobar = function(){
  $('#my_div').load('myurl');
  setTimeout('foobar',10000);
};
setTimeout('foobar',10000);

I found out, its working correctly (it updates the div every 10 seconds), but i detaches the old DOM (the whole site), and adds the new Response-DOM as new Content, thats very strange because if you click another page, and then use the Browser-Back Button, there are no styles, or Javascript. So very very very bad, i didn’t get the clue what went wrong.

Then i refactored it bit, so it looks like this:

foobar = function(){
  $('#my_div').load('myurl');
};
setInterval('foobar',10000);

And voila, its working as expected. It updates the div correctly, and leaves the rest of the DOM untouched.
Dont know whats the difference between those 2 examples?!

  1. we have real timers in flash. want them? ;)

Leave a Comment


NOTE - You can use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>