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();
    });

});
user1471980
  • 10,127
  • 48
  • 136
  • 235
  • 1
    Check out diff b/w setInterval and setTimeout. Also refrain from using string expression on these, use the function reference instead. – PSL Nov 04 '13 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. – Pekka Nov 04 '13 at 21:24
  • If you simply googled your title, your answer would have been in the first result... – Sumurai8 Nov 04 '13 at 21:24
  • @PSL, I am not very familiar with javascript, can you elaborate? – user1471980 Nov 04 '13 at 21:24
  • I was able to replace setTimeout with setInterval, it worked. Thanks everybody. – user1471980 Nov 04 '13 at 21:32

2 Answers2

3

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

monastic-panic
  • 3,987
  • 1
  • 22
  • 20
  • 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? – user1471980 Nov 05 '13 at 15:21
  • 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); – monastic-panic Nov 05 '13 at 15:55
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.

Andrei CACIO
  • 2,101
  • 15
  • 28