Javascript倒计时& setTimout错误

时间:2011-05-26 15:44:53

标签: javascript settimeout countdown

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这一行可能我在回忆函数时犯了错误 谁能告诉我哪里出错了?

THX

2 个答案:

答案 0 :(得分:1)

您不能在字符串中传递countdownDiv或endDate。替换:

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

使用:

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

设置为null是一种在某些浏览器中修复错误垃圾收集的肮脏技巧。

答案 1 :(得分:0)

setTimeout将函数作为第一个参数。删除前导和尾随引号