Simple JS Countdown

On our payments page at work I wanted to implement a visual countdown prior to redirecting users into their workspaces. After doing a bit of research I came up with the following solution:

See the Pen Simple JS Countdown by Justin Leatherwood (@jplwood) on CodePen.

Essentially I have a counter function:

function counter($el, n, func) {
  (function count() {
    $el.html(n);
    if (n--) {
      setTimeout(count, 1000);
    } else {
      func();
    }
  })();
}

And all you do is call that on a $('#countdown-button').click(function(){ ... }), telling it which element ($el) to put the counter in, how many seconds I want it to run for (n) and then I give it function to execute at the end of the countdown.

The function contains an immediately invoked function that utilizes setTimeout() to have the code pause for 1 second (1000 ms), and recursively call count() until n gets to 0.

Fun times. Weeeeeeeee yavascript!

Back to Blog