# How to Create a Countdown Timer in JavaScript

This tutorial will demonstrate how to create a countdown timer in JavaScript, including a function you can copy and paste into your own code.

The below code will break down creating a function which calculates the time until a certain future time, and how to run it repeatedly to affect a count down timer.

## Getting the time remaining until a certain date/time

The below function will calculate the days, hours, minutes, and seconds to a target date:

```function timeToTarget(countdownString){

// Convert the string which specifies the target to count down to to a Date object
let targetDate = new Date(countdownString).getTime();

// Get the current time
let now = new Date().getTime();

//The getTime() method gets a millisecond representation of the time since January 1st, 1970

//Get the difference between the two
let difference = targetDate - now;

// Calculate the days, hours, minutes, seconds difference between the times
days = Math.floor(difference / (1000 * 60 * 60 * 24));
hours = Math.floor(difference / (1000 * 60 * 60));
minutes = Math.floor(difference / (1000 * 60));
seconds = Math.floor(difference / 1000);

// Calculate the result
// As each of the above is the total days, hours, minutes, seconds difference, they need to be subtracted so that they add up to the correct total
let result =  {
days: days,
hours: hours - days * 24,
minutes: minutes - hours * 60,
seconds: seconds - minutes * 60,
};

// Log the result so we can check that the function is working
console.log(result);

// Return the result so that it can be used outside of the function
return result;
}```

## Counting Down with setInterval()

The JavaScript setInterval() method calls a given function repeatedly, with a fixed time delay between runs:

```setInterval(function(){
// Code to execute repeatedly here
}, 1000);```

Above, the function timeToTarget() is called every second (1000 milliseconds).

## Displaying the Countdown

To display the results of the countdown on a web page, a HTML element is required:

`<div id="countdown-display"></div>`

The following JavaScript can then be used to write the countdown information to the HTML element:

```document.getElementById("countdown-display").innerHTML =
'<div>' + result.days + '<span>Days</span></div>' +
'<div>' + result.hours + '<span>Hours</span></div>' +
'<div>' + result.result + '<span>Minutes</span></div>' +
'<div>' + result.seconds + '<span>Seconds</span></div>';```

## Putting It All Together

Finally, the date/time to countdown to needs to be specified as a string – this data could come from a date picker or other user input, or from a database:

`var countdownString = "Feb 7, 2023 19:30:00";`

Putting it all together, a working countdown timer!

```var countdownString = "Feb 7, 2023 19:30:00";

function timeToTarget(countdownString){

let targetDate = new Date(countdownString).getTime();
let now = new Date().getTime();
let difference = targetDate - now;

days = Math.floor(difference / (1000 * 60 * 60 * 24));
hours = Math.floor(difference / (1000 * 60 * 60));
minutes = Math.floor(difference / (1000 * 60));
seconds = Math.floor(difference / 1000);

let result =  {
days: days,
hours: hours - days * 24,
minutes: minutes - hours * 60,
seconds: seconds - minutes * 60,
};

console.log(result);

return result;

}

setInterval(function(){
let result = timeToTarget(countdownString);
document.getElementById("countdown-display").innerHTML =
'<div>' + result.days + '<span> Days</span></div>' +
'<div>' + result.hours + '<span> Hours</span></div>' +
'<div>' + result.minutes + '<span> Minutes</span></div>' +
'<div>' + result.seconds + '<span> Seconds</span></div>' +
'<div><span>Until </span>' + countdownString + '</div>';

}, 1000);```

SHARE: Author
I'm Brad, and I'm nearing 20 years of experience with Linux. I've worked in just about every IT role there is before taking the leap into software development. Currently, I'm building desktop and web-based solutions with NodeJS and PHP hosted on Linux infrastructure. Visit my blog or find me on Twitter to see what I'm up to.
{"ft_lang_label":"__label__en","ft_lang_prob":0.5919036,"math_prob":0.9229026,"size":3642,"snap":"2022-40-2023-06","text_gpt3_token_len":879,"char_repetition_ratio":0.16190214,"word_repetition_ratio":0.22140221,"special_character_ratio":0.30010983,"punctuation_ratio":0.15718563,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.96970415,"pos_list":[0,1,2],"im_url_duplicate_count":[null,null,null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2022-09-27T12:03:22Z\",\"WARC-Record-ID\":\"<urn:uuid:34d3c302-12f7-4214-91e0-4c941fcde595>\",\"Content-Length\":\"142141\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:eb54d59c-e667-42f6-8ff1-1b060c4bcd88>\",\"WARC-Concurrent-To\":\"<urn:uuid:560fdc7b-1da1-4720-990e-de71bf3f9e1f>\",\"WARC-IP-Address\":\"172.67.160.238\",\"WARC-Target-URI\":\"https://www.linuxscrew.com/javascript-countdown-timer\",\"WARC-Payload-Digest\":\"sha1:6AQVAP3B3WDFNUXEXRUDTVO6T2OD3J5Y\",\"WARC-Block-Digest\":\"sha1:QVWRJI4Z5S3PSCLKCD5WE2DRUGPQ2O6Q\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2022/CC-MAIN-2022-40/CC-MAIN-2022-40_segments_1664030335004.95_warc_CC-MAIN-20220927100008-20220927130008-00446.warc.gz\"}"}