125
<meta http-equiv="Refresh" Content="5">

This script reloads or refresh the page after every 5 seconds. But I want to do it using jQuery and AJAX call. Is it possible?

4 Answers 4

298

As others have pointed out setInterval and setTimeout will do the trick. I wanted to highlight a bit more advanced technique that I learned from this excellent video by Paul Irish: http://paulirish.com/2010/10-things-i-learned-from-the-jquery-source/

For periodic tasks that might end up taking longer than the repeat interval (like an HTTP request on a slow connection) it's best not to use setInterval(). If the first request hasn't completed and you start another one, you could end up in a situation where you have multiple requests that consume shared resources and starve each other. You can avoid this problem by waiting to schedule the next request until the last one has completed:

// Use a named immediately-invoked function expression.
(function worker() {
  $.get('ajax/test.html', function(data) {
    // Now that we've completed the request schedule the next one.
    $('.result').html(data);
    setTimeout(worker, 5000);
  });
})();

For simplicity I used the success callback for scheduling. The down side of this is one failed request will stop updates. To avoid this you could use the complete callback instead:

(function worker() {
  $.ajax({
    url: 'ajax/test.html', 
    success: function(data) {
      $('.result').html(data);
    },
    complete: function() {
      // Schedule the next request when the current one's complete
      setTimeout(worker, 5000);
    }
  });
})();
10
  • 4
    Isn't this like a recursive function call? If yes, then is it okay to let it run for a long period of time over and over, because it is recursive? can be a case of infinite recursion as long as ajax keeps successfully executing
    – Rahul Dole
    Commented Jul 23, 2013 at 14:18
  • 1
    Also, if you use setTimeout, then is there a way to stop this thread from outside this code-block? Like in setInterval, you can simply call clearInterval().
    – Rahul Dole
    Commented Jul 23, 2013 at 14:30
  • 19
    @RahulDole that's a good question but it is not recursive. It's not called directly from the worker function, so the stack won't continue to grow. For your second point, checkout the docs for setTimeout() and you'll see it returns a numerical id that can be passed to clearTimeout().
    – drewish
    Commented Jul 23, 2013 at 21:29
  • 7
    @RahulDole if you're in chrome play around with console.trace() to see a function's call stack. Functions invoked by setTimeout() will have a very short stack and it definitely won't include the function that called setTimeout().
    – drewish
    Commented Jul 24, 2013 at 20:16
  • 1
    @Anupal just create a new question.
    – drewish
    Commented Mar 9, 2015 at 18:27
40

Yes, you could use either the JavaScript setTimeout() method or setInterval() method to invoke the code that you would like to run. Here's how you might do it with setTimeout:

function executeQuery() {
  $.ajax({
    url: 'url/path/here',
    success: function(data) {
      // do something with the return value here if you like
    }
  });
  setTimeout(executeQuery, 5000); // you could choose not to continue on failure...
}

$(document).ready(function() {
  // run the first time; all subsequent calls will take care of themselves
  setTimeout(executeQuery, 5000);
});
1
  • 1
    Use just setTimeout(executeQuery, 5000); instead of setTimeout('executeQuery()', 5000); - it's shorter and faster.
    – rsp
    Commented Feb 19, 2011 at 18:20
4

You can use setTimeout or setInterval.

The difference is - setTimeout triggers your function only once, and then you must set it again. setInterval keeps triggering expression again and again, unless you tell it to stop

2

I tried the below code,

    function executeQuery() {
  $.ajax({
    url: 'url/path/here',
    success: function(data) {
      // do something with the return value here if you like
    }
  });
  setTimeout(executeQuery, 5000); // you could choose not to continue on failure...
}

$(document).ready(function() {
  // run the first time; all subsequent calls will take care of themselves
  setTimeout(executeQuery, 5000);
});

This didn't work as expected for the specified interval,the page didn't load completely and the function was been called continuously. Its better to call setTimeout(executeQuery, 5000); outside executeQuery() in a separate function as below,

function executeQuery() {
  $.ajax({
    url: 'url/path/here',
    success: function(data) {
      // do something with the return value here if you like
    }
  });
  updateCall();
}

function updateCall(){
setTimeout(function(){executeQuery()}, 5000);
}

$(document).ready(function() {
  executeQuery();
});

This worked exactly as intended.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.