setTimeOut() or setInterval() . 4 methods to apply same thing. which is best?
anonymous-function, javascript, jquery, setinterval, settimeout
Solution
The benefit of using #1 over #2 is that the `window` reference removes the chance of a scope variable overwriting `setInterval`.
// When out of global scope...
function setInterval() {
}
window.setInterval(foo, 100); // still calls the "correct" setInterval
There's no difference between wrapping the call to `countdown` in a function (#1, #2). #2 gives you greater flexibility as you can also call other functions/ pass arguments etc (although it's obviously trivial to swap from #1 to #2 if this becomes the case).
#4 saves you having to declare a function `clockStart`, other than that, it's the same as #3.
Use `clearTimeout` if you used `setTimeout`, and `clearInterval` if you used `setInterval`...
You should also be aware of how `setTimeout` and `setInterval` work differently. There's an amazing answer here which explains that...
As for what I'd use? I'd use #2.
Problem
I am displaying a countdown watch with respect to a given endtime. although its working perfect but i want to know which is best methods to apply. below is my countdown function. ``` var timerId; var postData = {endDate : endDate, tz : tz}; var countdown = function() { $.ajax({ type : 'post', async : false, timeout : 1000, url : './ajax_countdown.php', data : $.param(postData), dataType : 'json', success : function (resp){ $('#currentTime').html(resp.remainingTime); } }); } ``` what i want is that function (countdown) shoud be called automatically after every 1 second and if it does not execute/completed within 1 second then cancel the current ajax and start a new ajax call. now I found there are 4 working methods method 1: using setInterval() with window object ``` window.setInterval(countdown, 1000); ``` method 2 : using setInterval() independently ``` setInterval(function() {countdown()}, 1000); ``` method 3 : using setTimeOut inside the function an call other function to intialize main function ``` var countdown = function() { $.ajax({ //ajax code }); timerId = setTimeout(countdown, 5000); // assign to a variable } function clockStart() { if (timerId) return countdown(); } clockStart(); // calling this function ``` method 4 : using anonymous function call ``` var countdown = function() { $.ajax({ //ajax code }); timerId = setTimeout(countdown, 5000); } (function(){ if (timerId) return; countdown(); })(); ``` Please tell me - What is con and pro of each method and which one is best/right method? - Should i use `clearTimeOut()` or `clearInterval()` ? References http://javascript.info/tutorial/settimeout-setinterval Calling a function every 60 seconds http://www.electrictoolbox.com/using-settimeout-javascript/