Search code examples
javascriptsettimeoutcountdown

Javascript countdown & setTimout Error


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)
}

}

seem all works except the line with setTimeout probably I make a mistake on recall of the function.
Can anyone tell me where is the mistake?

thx


Solution

  • You cannot pass countdownDiv or endDate in a string. Replace:

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

    with:

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

    Setting to null is a dirty trick to fix for bad garbage collection in some browsers.