Friday, August 28, 2015

Build a Clock in 18 Lines of JavaScript with no Dependencies

Sometimes in life, you’re going to need a JavaScript countdown clock for something other than a doomsday device. Whether you have an event, a sale, a promotion, or a game, you can benefit from building a clock in raw JavaScript rather than reaching for the nearest plugin. While there are many great clock plugins, here are the benefits you’ll get from using raw JavaScript:

  • Your code will be lightweight because it will have zero dependencies.
  • Your website will perform better because you won’t need to load external scripts and style sheets.
  • You’ll have more control because you will have built the clock to behave exactly the way you want it to (rather than trying to bend a plugin to your will).

So, without further ado, here’s how to make your own countdown clock in a mere 18 lines of JavaScript.

Basic Clock: Count down to a Specific Date or Time

Here’s a quick outline of the steps involved in creating a basic clock:

  • Set a valid end date.
  • Calculate the time remaining.
  • Convert the time to a usable format.
  • Output the clock data as a reusable object.
  • Display the clock on the page, and stop the clock when it reaches zero.

Set a Valid End Date

First, you’ll need to set a valid end date. This should be a string in any of the formats understood by JavaScript’s Date.parse() method. For example:

The ISO 8601 format:

var deadline = '2015-12-31';

The short format:

var deadline = '31/12/2015';

Or, the long format:

var deadline = 'December 31 2015';

Each of these formats allows you to specify an exact time (in hours minutes and seconds), as well as a time zone (or an offset from UTC in the case of ISO dates). For example:

var deadline = 'December 31 2015 23:59:59 GMT+02:00';

You can read more about date formatting in JavaScript in this article.

Calculate the Time Remaining

The next step is to calculate the time remaining. To make that happen, we need to write a function that takes a string representing a given end time (as outlined above), and calculate the difference between that time and the current time. Here’s what that looks like:

function getTimeRemaining(endtime){
  var t = Date.parse(endtime) - Date.parse(new Date());
  var seconds = Math.floor( (t/1000) % 60 );
  var minutes = Math.floor( (t/1000/60) % 60 );
  var hours = Math.floor( (t/(1000*60*60)) % 24 );
  var days = Math.floor( t/(1000*60*60*24) );
  return {
    'total': t,
    'days': days,
    'hours': hours,
    'minutes': minutes,
    'seconds': seconds
  };
}

First, we’re creating a variable t, to hold the remaining time until the deadline. The Date.parse() function is native JavaScript that converts a time string into a value in milliseconds. This allows us to subtract two times from each other and get the amount of time in between.

var t = Date.parse(endtime) - Date.parse(new Date());

Convert the Time to a Usable Format

Now we want to convert the milliseconds to days, hours, minutes, and seconds. Let’s use seconds as an example:

var seconds = Math.floor( (t/1000) % 60 );

Let’s break down what’s going on here.

  1. Divide milliseconds by 1000 to convert to seconds: (t/1000)
  2. Divide the total seconds by 60 and grab the remainder—you don’t want all of the seconds, just the ones remaining after the minutes have been counted: (t/1000) % 60
  3. Round this down to nearest whole number—because you want complete seconds, not fractions of seconds: Math.floor( (t/1000) % 60 )

Repeat this logic to convert the milliseconds to minutes, hours, and days.

Output the Clock Data as a Reusable Object

With the days, hours, minutes, and seconds prepared, we’re now ready to return the data as a reusable object:

return {
  'total': t,
  'days': days,
  'hours': hours,
  'minutes': minutes,
  'seconds': seconds
};

This object allows you to call your function and get any of the calculated values. Here’s an example of how you’d get the remaining minutes:

getTimeRemaining(deadline).minutes

Convenient, right?

Display the Clock and Stop It When It Reaches Zero

Now that we have a function that spits out the days, hours, minutes, and seconds remaining, we can build our clock. First we’ll create the following HTML element to hold our clock:

<div id="clockdiv"></div>

Then we’ll write a function that outputs the clock data inside our new div:

function initializeClock(id, endtime){
  var clock = document.getElementById(id);
  var timeinterval = setInterval(function(){
    var t = getTimeRemaining(endtime);
    clock.innerHTML = 'days: ' + t.days + '<br>' +
                      'hours: '+ t.hours + '<br>' +
                      'minutes: ' + t.minutes + '<br>' +
                      'seconds: ' + t.seconds;
    if(t.total<=0){
      clearInterval(timeinterval);
    }
  },1000);
}

This function takes two parameters: the id of the element that will contain our clock and the end time of the countdown. Inside the function, we’ll declare a variable called clock and use it to store a reference to our clock container div so that we don’t have to keep querying the DOM.

Continue reading %Build a Clock in 18 Lines of JavaScript with no Dependencies%


by Yaphi Berhanu via SitePoint

No comments:

Post a Comment