JQuery - click button every 2 seconds

001 picture 001 · Jun 18, 2011 · Viewed 12k times · Source

Basically I have a refresh button, when the user clicks the refresh button it calls a web service, gets the data back and refreshes a div container to display the new data.

But I want to update the div container without having the user click the refresh button....

How do I have jquery click my button every 2 seconds, without refreshing the entire page? or is there a better way to do this?

Answer

Headshota picture Headshota · Jun 18, 2011

you can use setInterval to call a function after every given period of time:

setInterval(function(){ 
   $("#myBtn").click();
},2000);

this will invoke a click event on myBtn element in every 2 seconds.

Be careful, if you're sending an ajax request, it may sometimes need more time to receive a response, than your interval. this may cause some problems. so consider using recursive calls instead. (invoke click function from an ajax callback function)