0

I am trying to create a javascript which if I click on a div1, I need load_data1() function to refresh every 5 seconds. If the user clicks on div2 or div3, I need load_data1() function to stop. As the code below, when I click on the div1, load_data1() function runs after 5 second and stops, it does not run after that, any ideas what I might be missing here?

 $(document).ready(function(){ $.ajaxSetup({ cache: false }); var timeout; function timeout_init() { timeout=setTimeout('load_data1()', 5000); return timeout; } $("#div1").click(function() { timeout_init(); }); $("#div2").click(function() { clearTimeout(timeout); load_data2(); }); $("#div3").click(function() { clearTimeout(timeout); load_data3(); }); }); 
5
  • 1
    Check out diff b/w setInterval and setTimeout. Also refrain from using string expression on these, use the function reference instead. Commented Nov 4, 2013 at 21:22
  • For future reference, for goodness' sake please Google first. A simple search for how do you run a function every 5 seconds in javascript would have solved your problem. Commented Nov 4, 2013 at 21:24
  • If you simply googled your title, your answer would have been in the first result... Commented Nov 4, 2013 at 21:24
  • @PSL, I am not very familiar with javascript, can you elaborate? Commented Nov 4, 2013 at 21:24
  • I was able to replace setTimeout with setInterval, it worked. Thanks everybody. Commented Nov 4, 2013 at 21:32

2 Answers 2

3

you want to use setInterval() instead of setTimeout which only fires the one time, setInterval will keep firing until you clear it

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

2 Comments

I followed your recommendation it is working but I do have a concern. if the setInterval value is 60000ms, when I click on a tab, it waits 60000ms to load the page. I really need the page to load when clicked on the tab immediately then refresh every 60000ms. Any ideas how I would do this?
just call your function first before the setInterval. from your example in the timeout_init function, you can do load_data2(); setInterval(load_data2, 6000);
2

You can try something like this:

window.setInterval(function(){ /// call your function here }, 5000); 

It's an anonymous function that will run every 5 seconds.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.