Question

I want to make a function either using pure Javascript or also benefiting from jquery to count down to an ending time such as:

//consumes a javascript date object
function countDown(endtimme){
...
}

and it should display in html such as

<div id="time_left_box">
    <h1>Time remaining</h1>:

    <p>hours left: ..remaining day will be here## <p>
    <p>minutes left: ##remaining day will be here## <p>
    <p>seconds left: ##remaining day will be here## <p>
</div>

Indeed and it would be even more great if it can refresh itself every second.

I am very naive with javascript and confused about how to approach, any help would be appreciate.

Was it helpful?

Solution

You could use jQuery Countdown

OTHER TIPS

Take a look at this one: http://keith-wood.name/countdown.html

It can be done in JavaScript without plugins.

You need to get the current date time, down to the denominator that is one smaller than what you are displaying. With your example, this would mean you need to get everything down to milliseconds.

var currentTime = new Date(n.getFullYear(), n.getMonth(), n.getDate(), n.getHours(), n.getMinutes(), n.getSeconds(), n.getMilliseconds());

You then find the difference between now and the desired time. This is given to you in milliseconds.

var diff = endtime - currentTime;

Because this is returned in milliseconds you need to convert them into seconds, minutes, hours, days etc... This means establishing how many milliseconds are in each denominator. Then you are able to use mod and divide to return the number needed for each unit. See below.

var miliseconds = 1;
var seconds = miliseconds * 1000;
var minutes = seconds * 60;
var hours = minutes * 60;
var days = hours * 24;
var years = days * 365;

//Getting the date time in terms of units
//Floored so that they go together (to get just year/days/hours etc.. by themselves you need to use Math.round(diff/desired unit);
var numYears = Math.floor(diff / years);
var numDays = Math.floor((diff % years) / days);
var numHours = Math.floor((diff % days) / hours);
var numMinutes = Math.floor((diff % hours) / minutes);
var numSeconds = Math.round((diff % minutes) / seconds);

Once you have the denominators you want to display you can return this to the html page through different methods. For example:

document.getElementById("tyears").innerHTML = numYears;

That sums up your method. However, to make it run on a set interval (which is why you update the HTML display within the JavaScript function) you need to call the following function, giving your function name and provide your interval in terms of milliseconds.

//Call the count down timer function every second (measured in miliseconds)
setInterval(countDown(endtime), 1000);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top