Search code examples
c#jqueryasp.netjquery-countdown

Countdown timer going in minus instead of stopping on 0 days 00:00:00


I am dealing with this code for countdown timer in asp.net, jQuery, C#.

I have this jQuery code for the countdown timer:

<div id="timelabel"></div>
<script type="text/javascript">
var leave = <%=seconds %>;
CounterTimer();

var interv = setInterval(CounterTimer,1000);

function CounterTimer()
{
    var day = Math.floor(leave / ( 60 * 60 * 24))
    var hour = Math.floor(leave / 3600) - (day * 24)
    var minute = Math.floor(leave / 60) - (day * 24 *60) - (hour * 60)
    var second = Math.floor(leave) - (day * 24 *60*60) - (hour * 60 * 60) -(minute*60)

    hour = hour < 10 ? "0" + hour : hour;
    minute = minute < 10 ? "0" + minute : minute;
    second = second<10 ? "0" + second : second;

    var remain = day + " days   " + hour + ":" + minute + ":" + second;
    leave = leave - 1;

    document.getElementById("timelabel").innerText = remain;
}
</script>

And I am passing end date from code behind file that is .cs:

public double seconds;

protected void Page_Load(object sender, EventArgs e)
{
    seconds = (GetEndTime() - GetStartTime()).TotalSeconds;
}

private DateTime GetStartTime()
{
    return DateTime.Now;
}

private DateTime GetEndTime()
{
    return new DateTime(2016, 6, 12, 11, 57, 00); //end date yr-month-day hr-mnt-sec
}

I am facing a problem that this timer wont stops when it hits 0 days 00:00:00 it goes beyond that like -1 days 23:48:20. I want to fix this as I don't have that much knowledge about jQuery I am finding it pretty difficult so can someone guide me with needed modifications? Please help. Thank you in advance.


Solution

  • You need to clear interval after it goes to 0 or beyond. Add this to the bottom of your CounterTimer function.

    if(leave <= 0) clearInterval(interv);