Gopinath Koothaperumal
Gopinath Koothaperumal

Reputation: 398

Countdown timer in javascript using setTimeout

i'm creating a countdown timer using jquery, i refered to a few example here and came out with the following codes. The problem is the time doesn't show, and i can't figure out what is wrong. Been stuck for almost 2 hours..

back code

    var day = 1;                        //countdown time
    var start = player.LastActive;      // Use UtcNow instead of Now
    var endTime = start.AddDays(day);   //endTime is a member, not a local variable
    Timespan remainingTime = endTime - DateTime.UtcNow;

my javascript

var endTime = '<%= remainingTime%>';
var startTime = '<%= DateTime.UtcNow %>'

$(document).load(function () {
        countDown(endTime);
    });

    function countDown(endTime) {
        if (endTime > 0) {
            var d = document.getElementById("countDiv");
            d.innerHTML = endTime;
            setTimeout(function () { countDown(endTime - 1); }, 1000);
        }
    }

my html

<div id="countDiv" style="float:left;margin-top: 13px; margin-left:5px;"></div>

my goal is to show how long more, for a player to get his daily move : which is a day after the players lastactive time. Can someone enlighten me..thank u

Upvotes: 1

Views: 2842

Answers (4)

Rapha&#235;l Althaus
Rapha&#235;l Althaus

Reputation: 60493

use $(window).load

or

$(document).ready

but not $(document).load

and as you seem to use jquery, you can do

$(document).ready(function () {
        countDown(endTime);
    });

    function countDown(endTime) {
        if (endTime > 0) {
            $('#countDiv').text(secondsToTime(endTime));
            setTimeout(function () { countDown(endTime - 1); }, 1000);
        }
    }
function secondsToTime(secs)
{
    var hours = Math.floor(secs / (60 * 60));

    var divisor_for_minutes = secs % (60 * 60);
    var minutes = Math.floor(divisor_for_minutes / 60);

    var divisor_for_seconds = divisor_for_minutes % 60;
    var seconds = Math.ceil(divisor_for_seconds);

    return hours +':' + minutes + ':' + seconds;
}

for seconds to time, it's coming from https://stackoverflow.com/a/6312999/961526 , you may take another version which you can find there.

see jsFiddle

Upvotes: 2

Markus_DE_HH
Markus_DE_HH

Reputation: 1071

Or try this

  $(function() {
            countDown(endTime);
       });

 function countDown(parseInt(endTime)) {
        if (endTime > 0) {
            $('#countDiv').text(endTime);
            setTimeout(function () { countDown(endTime - 1); }, 1000);
        }
    }

Upvotes: 0

Andy
Andy

Reputation: 63587

ready, not load.

$(document).ready(function () {
  countDown(endTime);
});

Upvotes: 0

Voonic
Voonic

Reputation: 4785

Since your endtime is string in your javascript code, convert it integer first

try this

$(document).ready(function () {
        countDown(parseInt(endTime));
    });

Upvotes: 2

Related Questions