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?

informatik01
  • 16,038
  • 10
  • 74
  • 104
user12345
  • 2,400
  • 8
  • 33
  • 40

4 Answers4

296

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);
    }
  });
})();
GAMITG
  • 3,810
  • 7
  • 32
  • 51
drewish
  • 9,042
  • 9
  • 38
  • 51
  • 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 Jul 23 '13 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 Jul 23 '13 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 Jul 23 '13 at 21:29
  • That was a valuable information @drewish! So you are saying that the reason why it's not recursive is because it is called from the ajax block? That's interesting. And yes, i had noticed once that setTimeout() returns a numerical id, but didn't know about clearTimeout(). I'll try it out – Rahul Dole Jul 24 '13 at 05:16
  • 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 Jul 24 '13 at 20:16
  • I need help. Can we run AJAX calls in to active window only and abort in all other multiple windows opened. how we can do that as if any person has opened the same website in 10 different windows then that AJAX will run in all windows that will consume more resources, Please any help? – Anupal Mar 07 '15 at 05:20
  • 1
    @Anupal just create a new question. – drewish Mar 09 '15 at 18:27
  • I 'm using in complete setTimeout(executeQuery, 3600000); // for every hour. But it seems to run continuously, console of chrome keep on changing with new calls. why its happening? – Muhammad Faisal Iqbal Jan 03 '17 at 12:07
  • 1
    @MuhammadFaisalIqbal open a new question with more of your sample code so people can see exactly what you're trying to do. based on that tiny sample it should be fine. i'd suspect your scheduling multiple timers someplace. – drewish Jan 03 '17 at 16:41
  • Idea: Use timeout inside the ajax request. A timeout lower thant the setTimeout/setInterval – pablo_worker Jul 11 '19 at 16:09
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);
});
Ajinkya
  • 22,324
  • 33
  • 110
  • 161
Tahbaza
  • 9,486
  • 2
  • 26
  • 39
  • 1
    Use just setTimeout(executeQuery, 5000); instead of setTimeout('executeQuery()', 5000); - it's shorter and faster. – rsp Feb 19 '11 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

Ajinkya
  • 22,324
  • 33
  • 110
  • 161
Puneet
  • 1,014
  • 1
  • 8
  • 14
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.

Srihari
  • 43
  • 3