001
001

Reputation: 65205

JQuery - click button every 2 seconds

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?

Upvotes: 2

Views: 14786

Answers (3)

Headshota
Headshota

Reputation: 21449

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)

Upvotes: 10

mu is too short
mu is too short

Reputation: 434935

You could use setInterval to run a function every two seconds:

Calls a function repeatedly, with a fixed time delay between each call to that function.

And then have the called function call the button's click handler. Ideally you'd be able to call the click handler directly without have to say $x.click().

Using setTimeout might be a better idea:

Executes a code snippet or a function after specified delay.

Then the callback function would call the click handler and, when that finishes, it would call setTimeout again to trigger itself. This approach will keep your timed events from overrunning each other. Since all the code is yours, you can restructure it so that the $.ajax success and error callbacks (or perhaps the complete callback) could restart the timer.

Upvotes: 3

Kranu
Kranu

Reputation: 2567

You can do this with clean old javascript using the setInterval command. Here is an example:

//Run updates every 2 seconds
var x=setInterval(doUpdates,2000);
function doUpdates() {
  //Do whatever updating you need
}

If you want to stop the automatic updates here, you can use the command clearInterval(x);.

If the refreshing of data takes a long time, you can make it so that there is 2 second interval between each request.

function doUpdates() {
  //Do whatever updating you need
  $.ajax({
    'success':function() {
      setTimeout(doUpdates,2000);
    }
  });
}

For the second example, you would place the setTimeout directly after the refreshing is complete.

Upvotes: 0

Related Questions