2011-05-26 110 views
0
function initCountdown(countdownDiv, endDate, endMsg) { 

current_date = new Date();         
time_left = endDate.getTime() - current_date.getTime(); 

if(time_left>0) { 
    time_left = Math.floor(time_left/1000);     
    days=0;hours=0;mins=0;secs=0;out="";     

    days=Math.floor(time_left/86400); 
    time_left=time_left%86400; 

    hours=Math.floor(time_left/3600); 
    time_left=time_left%3600; 

    mins=Math.floor(time_left/60); 
    time_left=time_left%60; 

    secs=Math.floor(time_left);    

    var daysTxt = "<strong>"+days +"</strong>day"+((days!=1)?"s":"");      
    var hoursTxt = "<strong>"+hours +"</strong>hour"+((hours!=1)?"s":""); 
    var minTxt = "<strong>"+mins +"</strong>min"+((mins!=1)?"s":""); 
    var secTxt = "<strong>"+secs +"</strong>sec"; 

    var finalTxt = daysTxt + " : " + hoursTxt+ " : " + minTxt + " : "+ secTxt; 
    $(countdownDiv).html(finalTxt) 

    setTimeout("initCountdown('"+ countdownDiv +"', '"+ endDate +"', '"+ endMsg +"')", 1000); 
}else{ 
    $(countdownDiv).html(endMsg) 
} 

} 

似乎所有的作品,除了行setTimeout可能我犯了一個錯誤的函數回憶。
誰能告訴我哪裏錯了?Javascript倒計時&setTimout錯誤

thx

+1

不要將字符串傳遞給'setTimeout'。 – SLaks 2011-05-26 15:46:39

回答

1

您不能在字符串中傳遞countdownDiv或endDate。替換:

setTimeout("initCountdown('"+ countdownDiv +"', '"+ endDate +"', '"+ endMsg +"')", 1000); 

有:

setTimeout(function(){initCountdown(countdownDiv, endDate, endMsg); countdownDiv = null; endDate = null; endMsg = null}, 1000); 

設置爲NULL是一個卑鄙的手段來解決在某些瀏覽器壞垃圾收集。

0

setTimeout將函數作爲第一個參數。刪除前導和尾隨引號