2011-05-26 96 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将函数作为第一个参数。删除前导和尾随引号