Skip to content

Instantly share code, notes, and snippets.

@schalkneethling
Created July 8, 2022 15:23
Show Gist options
  • Save schalkneethling/de2b103e3b9a9259f7a10477b943523d to your computer and use it in GitHub Desktop.
Save schalkneethling/de2b103e3b9a9259f7a10477b943523d to your computer and use it in GitHub Desktop.
A simple JavaScript countdown timer
(function () {
dayjs.extend(window.dayjs_plugin_duration);
const launchDay = Date.parse("2022-06-10T21:00:00Z");
const daysOutput = document.getElementById("countdown-days");
const hoursOutput = document.getElementById("countdown-hours");
const minutesOutput = document.getElementById("countdown-minutes");
const secondsOutput = document.getElementById("countdown-seconds");
let duration;
setInterval(() => {
duration = dayjs.duration(launchDay - Date.now());
daysOutput.textContent = duration["$d"].days;
hoursOutput.textContent =
duration["$d"].hours > 9
? duration["$d"].hours
: `0${duration["$d"].hours}`;
minutesOutput.textContent =
duration["$d"].minutes > 0
? duration["$d"].minutes
: `0${duration["$d"].minutes}`;
secondsOutput.textContent =
duration["$d"].seconds > 9
? duration["$d"].seconds
: `0${duration["$d"].seconds}`;
}, 100);
})();
@schalkneethling
Copy link
Author

Hey @ctessmer - I have not used Alpine, but if the primary problem is the anonymous function you can turn this into a named function. The primary reason this was written as is, is so that it will start as soon as the DOM is "ready" in a sense.

You could also do the following:

const startClock = () => {
  dayjs.extend(window.dayjs_plugin_duration);

  const launchDay = Date.parse("2022-06-10T21:00:00Z");

  const daysOutput = document.getElementById("countdown-days");
  const hoursOutput = document.getElementById("countdown-hours");
  const minutesOutput = document.getElementById("countdown-minutes");
  const secondsOutput = document.getElementById("countdown-seconds");

  let duration;

  setInterval(() => {
    duration = dayjs.duration(launchDay - Date.now());
    daysOutput.textContent = duration["$d"].days;
    hoursOutput.textContent =
      duration["$d"].hours > 9
        ? duration["$d"].hours
        : `0${duration["$d"].hours}`;
    minutesOutput.textContent =
      duration["$d"].minutes > 0
        ? duration["$d"].minutes
        : `0${duration["$d"].minutes}`;
    secondsOutput.textContent =
      duration["$d"].seconds > 9
        ? duration["$d"].seconds
        : `0${duration["$d"].seconds}`;
  }, 100);
};

Wherever you want to kick it off, you can call startClock(); - I hope this helps.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment