开发者

Problem with live countdown clock

Basically I currently have the clock presenting the time however the countdown isn't working. I have taken the code originally from here and have adapted it.

What I am trying to do is get the countdown to count down from a duration time I have retrieved from my database.

here is how I retrieve my duration time:

//TRANSFORM MYSQL TIME INTO SECONDS

    $duration_array = explode(':', $duration);

    $length = ((int)$duration_array[0] * 3600) + ((int)$duration_array[1] * 60) + (int)$duration_array[2];

    //CALCULATE FINISH TIME WITH START TIME AND DURATION.
    $target_time = $length + time();

I am parsing this to my JavaScript countdown function successfully and converting into a javascript date() object.

However currently the clock doesn't count down.

Here is my javascript:

function countdown_clock(target_time)
         {
         html_code = '<div id="countdown"></div>';

         document.write(html_code);

     var timetarget = new Date(target_time *1000);

         countdown(timetarget);

         }


function countdown(timetarget)
         {

     var Today = new Date();

     Todays_Year = Today.getFullYear() - 2000;
         Todays_Month = Today.getMonth();

         //Convert both today's date and the target date into miliseconds.
         Todays_Date = (new Date(Todays_Year, Todays_Month, Toda开发者_Python百科y.getDate(),Today.getHours(),Today.getMinutes(),Today.getSeconds())).getTime();

     Target_Date = timetarget.getTime();

         //Find their difference, and convert that into seconds.
         Time_Left = Math.round((Target_Date - Todays_Date) / 1000);

         if(Time_Left < 0)
            Time_Left = 0;

        var innerHTML = '';

         //More datailed.
        days = Math.floor(Time_Left / (60 * 60 * 24));
        Time_Left %= (60 * 60 * 24);
        hours = Math.floor(Time_Left / (60 * 60));
        Time_Left %= (60 * 60);
        minutes = Math.floor(Time_Left / 60);
        Time_Left %= 60;
        seconds = Time_Left;

    if (seconds < 10){seconds = '0' + seconds;}
    if (minutes < 10){minutes = '0' + minutes;}

        innerHTML = hours + ':' + minutes + ':' + seconds + ' secs' ;

        document.getElementById('countdown').innerHTML = innerHTML;

         //Recursive call, keeps the clock ticking.
        setTimeout('countdown('+timetarget+');', 1000);
        }

I really seem to be struggling with the whole date stuff so any help would be great.

thanks,


I think the issue was that your timetarget variable was losing the fact that it was a Date object. I fixed it and made a jsFiddle, and it seems to be working (counting down).

EDIT: additionally, I think Javascript might have been screwing up because you were using innerHTML as a variable name, and that's another change I made.

EDIT 2: here's an update with some slightly cleaned up code.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜