Saturday, November 24, 2018

jquery - how do you run a function every 5 seconds in javascript





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

});

});

Answer



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


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...