DEV Community

Huy Do
Huy Do

Posted on

Countdown Timer part 2

Schedule the Clock Automatically

Let’s say we want the clock to show up on certain days but not others. For example, we might have a series of events coming up and don’t want to manually update the clock each time. Here’s how to schedule things in advance.

Hide the clock by setting its display property to none in the CSS. Then add the following to the initializeClock function (after the line that begins with var clock). This will cause the clock to only display once the initializeClock function is called:

clock.style.display = 'block';
Enter fullscreen mode Exit fullscreen mode

Next we can specify the dates between which the clock should show up. This will replace the deadline variable:

const schedule = [
    ['Jul 25 2015', 'Sept 20 2015'],
    ['Sept 21 2015', 'Jul 25 2016'],
    ['Jul 25 2016', 'Jul 25 2030']
];
Enter fullscreen mode Exit fullscreen mode

Each element in the schedule array represents a start date and an end date. As noted above, it is possible to include times and time zones, but I used plain dates here to keep the code readable.

Finally, when a user loads the page, we need to check if we are within any of the specified time frames. This code should replace the previous call to the initializeClock function.

// iterate over each element in the schedule
for (var i=0; i<schedule.length; i++) {
  var startDate = schedule[i][0];
  var endDate = schedule[i][1];

  // put dates in milliseconds for easy comparisons
  var startMs = Date.parse(startDate);
  var endMs = Date.parse(endDate);
  var currentMs = Date.parse(new Date());

  // if current date is between start and end dates, display clock
  if (endMs > currentMs && currentMs >= startMs ) {
    initializeClock('clockdiv', endDate);
  }
}

schedule.forEach(([startDate, endDate]) => {
  // put dates in milliseconds for easy comparisons
  const startMs = Date.parse(startDate);
  const endMs = Date.parse(endDate);
  const currentMs = Date.parse(new Date());

  // if current date is between start and end dates, display clock
  if (endMs > currentMs && currentMs >= startMs ) {
    initializeClock('clockdiv', endDate);
  }
});
Enter fullscreen mode Exit fullscreen mode

Now you can schedule your clock in advance without having to update it by hand. You may shorten the code if you wish.

Set Timer for 10 Minutes from When the User Arrives

It may be necessary to set a countdown for a given amount of time after the user arrives or starts a specific task. We’ll set a timer for 10 minutes here, but you can use any amount of time you want.

All we need to do here is replace the deadline variable with this:

const timeInMinutes = 10;
const currentTime = Date.parse(new Date());
const deadline = new Date(currentTime + timeInMinutes*60*1000);
Enter fullscreen mode Exit fullscreen mode

This code takes the current time and adds ten minutes. The values are converted into milliseconds, so they can be added together and turned into a new deadline.

Maintain Clock Progress across Pages

Sometimes it’s necessary to preserve the state of the clock for more than just the current page. If we wanted to set a 10-minute timer across the site, we wouldn’t want it to reset when the user goes to a different page.

One solution is to save the clock’s end time in a cookie. That way, navigating to a new page won’t reset the end time to ten minutes from now.

Here’s the logic:

If a deadline was recorded in a cookie, use that deadline.
If the cookie isn’t present, set a new deadline and store it in a cookie.
To implement this, replace the deadline variable with the following:

let deadline;

// if there's a cookie with the name myClock, use that value as the deadline
if(document.cookie && document.cookie.match('myClock')){
  // get deadline value from cookie
  deadline = document.cookie.match(/(^|;)myClock=([^;]+)/)[2];
} else {
  // otherwise, set a deadline 10 minutes from now and 
  // save it in a cookie with that name

  // create deadline 10 minutes from now
  const timeInMinutes = 10;
  const currentTime = Date.parse(new Date());
  deadline = new Date(currentTime + timeInMinutes*60*1000);

  // store deadline in cookie for future reference
  document.cookie = 'myClock=' + deadline + '; path=/; domain=.yourdomain.com';
}
Enter fullscreen mode Exit fullscreen mode

This code makes use of cookies and regular expressions, both of which are separate topics in their own right. For that reason, I won’t go into too much detail here. The one important thing to note is that you’ll need to change .yourdomain.com to your actual domain.

An Important Caveat about Client-Side Time

JavaScript dates and times are taken from the user’s computer. That means the user can affect a JavaScript clock by changing the time on their machine. In most cases, this won’t matter. But in the case of something super sensitive, it will be necessary to get the time from the server. That can be done with a bit of PHP or Ajax, both of which are beyond the scope of this tutorial.

After getting the time from the server, we can work with it using the same techniques from this tutorial.

References:
https://dev.to/huyddo/countdown-timer-7lg
https://www.sitepoint.com/build-javascript-countdown-timer-no-dependencies/
https://codepen.io/SitePoint/pen/NWxKgxN

Top comments (0)