setTimeOut () или setInterval (). 4 способа применить одно и то же. какой лучше?
Я показываю часы обратного отсчета в отношении заданного времени окончания.
хотя он работает идеально, но я хочу знать, какие методы лучше всего применять.
ниже моя функция обратного отсчета.
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);
}
});
}
что я хочу, так это то, что функция (обратный отсчет) должна быть вызванаautomatically after every 1 second и если он не будет выполнен / завершен в течение 1 секунды, отмените текущий ajax и начните новый вызов ajax.
теперь я обнаружил, что есть4 working methods
method 1: using setInterval() with window objectwindow.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();
})();
пожалуйста, скажите мне
What is con and pro of each method and which one is best/right method? Should i useclearTimeOut()
or clearInterval()
?
References
http://javascript.info/tutorial/settimeout-setinterval Calling a function every 60 seconds http://www.electrictoolbox.com/using-settimeout-javascript/