QR Code contains TinyURL of this article.Day-sensitive Countdown Timer

Let’s say you’re running an e-commerce website and you’re offering same-day shipping on orders placed before 3pm, Monday–Friday. A user interface widget should advise customers of how long they have left to complete their order in order to take advantage of this offer.

The widget should indicate the remaining hours, minutes and seconds. It should count down in real-time. It should not count down on Saturdays or Sundays. The timer should automatically reset at midnight, Sunday–Thursday.

I recently had to satisfy these requirements on a client’s website. I came up with a pure JavaScript solution (no dependencies) as follows:

Demo

A working demo is available.

Usage

Download caseSensitiveCountdownTimer.js and upload it to your website.

Include the file on the page(s) you wish to display the timer on:

<script type="text/javascript" src="path/to/caseSensitiveCountdownTimer.js"></script>

Use the following code to display the timer:

<span id="countdownTimer">00:00.<small>00</small></span>

for example:

<p>Time Remaining: <span id="countdownTimer">00:00.<small>00</small></span></p>

(view the source of the demo page if this is not clear).

In the caseSensitiveCountdownTimer.js file, there are two things you might need to edit. The first is to adjust the time you want to count down to. Look for the following line in the code:

var target = 15;

Replace “15” with your target hour. Note that we’re using the 24-hour clock here thus: 15 equates to 3pm; 0 would be midnight; 7 would be 7am.

The second thing you might want to change is the days that the timer runs on. By default, it will run Monday–Friday. Look for the following line in the code:

if ( (now.getDay() >= 1) && (now.getDay() <= 5) ) {

The “1” is the start day and “5” is the end day. To run seven days a week, adjust as follows:

if ( (now.getDay() >= 0) && (now.getDay() <= 6) ) {

To only run on Thursdays:

if (now.getDay() == 4) {

Note that JavaScript counts days from Sunday and starting at 0.
Thus: Sunday = 0; Wednesday = 3; Saturday = 6.

Code

This project is on GitHub.