Search code examples
jqueryweb-servicesjquery-eventspartial-page-refresh

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?


Solution

  • 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.