Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Some links on this page are affiliate links: if you buy through them we may earn a commission, at no extra cost to you.

Connect the countdown to a button’s click handler, keep the timer’s ID in a separate variable, and call audio.play() when the countdown reaches zero. Because browsers can reject scripted playback, handle the Promise returned by play() and give users a visible completion message as well as a sound.

A working countdown with a completion sound

This example starts a five-second countdown when the user clicks Start. It displays 5 immediately, updates the displayed number once per second, and attempts to play the sound once at zero. Replace finish.mp3 with the path to your audio file.

<button id="startButton" type="button">Start countdown</button>
<button id="resetButton" type="button" disabled>Reset</button>

<p id="countdown" aria-live="polite">5</p>
<p id="status" role="status">Ready.</p>

<audio id="finishSound" preload="auto" controls>
  <source src="finish.mp3" type="audio/mpeg">
</audio>

<script>
  const startButton = document.querySelector("#startButton");
  const resetButton = document.querySelector("#resetButton");
  const countdownDisplay = document.querySelector("#countdown");
  const status = document.querySelector("#status");
  const finishSound = document.querySelector("#finishSound");

  const duration = 5;
  let timerId = null;
  let endTime = null;

  function updateCountdown() {
    const secondsRemaining = Math.max(
      0,
      Math.ceil((endTime - performance.now()) / 1000)
    );

    countdownDisplay.textContent = secondsRemaining;

    if (secondsRemaining === 0) {
      clearInterval(timerId);
      timerId = null;
      startButton.disabled = false;
      resetButton.disabled = false;
      status.textContent = "Countdown complete.";

      finishSound.currentTime = 0;
      finishSound.play()
        .then(() => {
          status.textContent = "Countdown complete. Sound played.";
        })
        .catch((error) => {
          console.error("Audio playback failed:", error);
          status.textContent =
            "Countdown complete, but the sound could not play. Try the audio controls.";
        });

      return;
    }

    status.textContent = `${secondsRemaining} second${secondsRemaining === 1 ? "" : "s"} remaining`;
  }

  function startCountdown() {
    if (timerId !== null) return;

    startButton.disabled = true;
    resetButton.disabled = false;
    endTime = performance.now() + duration * 1000;

    updateCountdown();
    timerId = setInterval(updateCountdown, 100);
  }

  function resetCountdown() {
    if (timerId !== null) {
      clearInterval(timerId);
      timerId = null;
    }

    endTime = null;
    countdownDisplay.textContent = duration;
    status.textContent = "Ready.";
    startButton.disabled = false;
    resetButton.disabled = true;

    finishSound.pause();
    finishSound.currentTime = 0;
  }

  startButton.addEventListener("click", startCountdown);
  resetButton.addEventListener("click", resetCountdown);
</script>

The controls attribute exposes the browser’s audio controls. You can remove it for a cleaner interface, but retaining it gives users a way to try the sound manually if scripted playback is blocked. See MDN’s documentation for audio controls.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Why this code stores a deadline

The example uses setInterval() to refresh the display, but it does not subtract one from a counter on every callback. Instead, it calculates the remaining time from a target end time using performance.now(). A requested 1,000-millisecond timer delay is not a promise that the callback will run exactly one second later; browser scheduling and background-tab throttling can delay it. A deadline helps the displayed countdown catch up rather than accumulating that delay. MDN explains interval timing and cancellation.

#1 Best Overall
Amazon Basics Stereo 2.0 Speakers for PC or Laptop with Volume Control, 3.5mm Aux Input, USB-Powered, 1 Pair, Black
  • External computer speaker in Black (set of 2) for amplifying PC or laptop audio
  • USB-Powered from USB port of PC or Laptop
  • In-line volume control for easy access
  • Blue LED lights; metal finish and scratch-free padded base
  • Bottom radiator for “springy” bass sound

The interval runs every 100 milliseconds so the display can notice the deadline promptly, but the displayed whole-second value changes only when the remaining second changes. For a very short, informal countdown, a recursive setTimeout() can also work; neither timer API is a precision clock. If the tab is hidden and later shown, you can refresh the display immediately:

document.addEventListener("visibilitychange", () => {
  if (!document.hidden && timerId !== null) {
    updateCountdown();
  }
});

Keep the timer ID separate from the countdown number

setInterval() returns an identifier for the scheduled interval. Save that value and pass it to clearInterval() when the countdown ends or is reset:

let remaining = 5;
const timerId = setInterval(update, 1000);
clearInterval(timerId);

Do not call clearInterval(remaining): the remaining number is application state, not the timer identifier. Confusing the two can leave the interval running. The original discussion of this problem also notes that repeated clicks can start overlapping countdowns: SitePoint’s countdown-and-sound thread.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #2
Computer Speakers for Desktop PC Monitor, USB Plug-in, Wired, Computer Soundbar for PC, Laptop Speakers with Adaptive-Channel-Switching, Loud Sound, Deep Bass, USB C Adapter, Easy to Clip on Monitor
  • [COMPATIBLE WITH USB DEVICES] - Our USB Speakers are compatible with Windows, macOS, ChromeOS, and Linux, making them ideal for PC, laptop, and desktop computer. Incompatible Devices: Monitors TVs and Projector.
  • [COMPATIBLE WITH USB-C DEVICES] - Thanks to the built-in USB-C to USB Adapter, our USB-C speakers are now compatible with devices that only have USB-C interface, such as the latest MacBook, Mac mini, iMac, iPad, Android phones, and tablets.
  • [INCREDIBLE LOUD SOUND WITH RICH BASS] - Our small computer speaker is equipped with dual ultra-magnetic drivers and dual passive radiators, providing high-quality stereo sound with powerful volume and deep bass for an incredible audio experience.
  • [ADAPTIVE-CHANNEL-SWITCHING WITH G-SENSOR] - Ensures the left and right sound channels remain correctly positioned whether the speaker is clamped to the top or bottom of your monitor.
  • [CONVENIENT TOUCH CONTROL] - Three intuitive touch buttons on the front allow for easy muting and volume adjustment.

The example prevents duplicate starts in two ways: it disables the Start button while running and checks timerId inside the handler. The state check is important even when the button is disabled; it makes the function itself refuse a second start. Reset clears the active interval, restores the starting display and stops or rewinds the audio.

Why the sound may not play

A countdown reaching zero does not guarantee that audible playback begins. HTMLMediaElement.play() returns a Promise: it resolves when playback starts and can reject if the browser or platform does not allow it. NotAllowedError commonly indicates a playback-policy restriction; NotSupportedError can indicate an unsupported source or format. Handle rejection rather than assuming that calling play() succeeded. See MDN’s documentation for play().

A click on Start is a user action, but it does not universally guarantee that a later, timer-triggered play call will be allowed. Browser policy, device settings, muted tabs, and iframe permissions can all matter. MDN’s autoplay guide describes the policy issue; the autoplay Permissions Policy documentation covers embedded documents. Do not treat the autoplay attribute as a guarantee either: browsers may block audible autoplay. See MDN on the autoplay property.

Rank #3
LENRUE G11 Computer Speakers for Desktop, Touch Lights PC Speakers with Surge Clear Sound, USB C/USB Powered, AUX Audio for Computer Desktop PC Laptop Desk
  • Surge Stereo Sound - 4 large amplifier IC horns! Computer speakers achieved Distortion Free and Noiseless in stunning sound. Immersive cinema effect for movies, videos, games and music.
  • Touch Angular Game Lights - Unique Dynamic Angular Game Atmosphere design! Desktop speaker with latest One Touch to turn on/off lights, avoid the traditional cumbersome button design.
  • All In One Compact - Fits any desktop computer! Perfectly under the monitor without taking up any extra desktop space. Cables are glued together to avoid desktop clutter.
  • Plug And Play - No need for any driver! Must Plug in the USB powered cable and 3.5mm audio cable to enjoy now! Top volume knob for easier volume adjustment.
  • Type C Adapter Included & Compatibility - USB speakers match computers, desktops, PCs, laptops. Suitable for windows(Vista/7/8/10), Mac OS, Chrome OS, etc.

If playback fails, check these separately:

  • Playback permission: Look for a rejected play() Promise, especially NotAllowedError. Offer an explicit way to play the sound, such as the visible audio controls, and keep the on-screen completion message.
  • File path and loading: Confirm that the URL is correct relative to the page and that the file loads successfully in the browser. A missing file or server response problem is not the same as an autoplay restriction.
  • Format and source: Use a format supported by the browsers you target. Support can vary; if needed, supply more than one source, as in the example below.
  • Muted output or silence: Check the device and tab volume. A file with silence at its beginning can make playback seem late; trim the leading silence if timing matters.
  • Loading and latency: preload="auto" asks the browser to prepare the media, but does not guarantee instant loading or playback. Network delay and output-device latency can affect when the sound is heard.

To test the source independently from the countdown, temporarily expose native controls or open the media URL directly. Multiple formats can be listed like this:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
<audio id="finishSound" preload="auto" controls>
  <source src="finish.mp3" type="audio/mpeg">
  <source src="finish.ogg" type="audio/ogg">
</audio>

Do not assume that a format works in every browser; verify the formats required by your audience. For a real-world example of delayed playback being rejected with NotAllowedError, see this Stack Overflow question.

Play a sound on every tick instead

If you mean a beep for every number rather than one sound at completion, trigger a separate sound when the displayed value changes. Reuse a preloaded element and rewind it before each attempt:

Rank #4
Sale
Logitech Z207 2.0 Stereo Computer Speakers with Bluetooth
  • Versatile setup with speakers that connect easily to computers and other devices via Bluetooth wireless or 3.5mm cable
  • Logitech Easy-Switch technology lets you seamlessly switch between audio devices Just by pausing the Audio on one device and pressing play on the other
  • Each speaker has one active/powered driver that delivers full range Audio and ONE passive radiator that provides bass extension.
  • On-speaker headphone jack Plus convenient controls for easy access to Bluetooth wireless pairing, power and Volume adjustments, Bluetooth version: 4.2
  • Works with Bluetooth enabled devices and any device with a 3.5mm input including a computer, television, smartphone, tablet and music player
const tickSound = document.querySelector("#tickSound");

function playTick() {
  tickSound.currentTime = 0;
  tickSound.play().catch((error) => {
    console.error("Tick sound failed:", error);
  });
}

Call playTick() only when the displayed number changes. If a sound is longer than the interval between ticks, playback may overlap or be cut off when rewound. For a spoken countdown, speech synthesis is a separate option with its own timing and voice availability considerations; it is not a drop-in replacement for a sound file.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

A short version for a simple countdown

For a small page where drift correction and reset are not important, a recursive timeout is straightforward. This version displays the initial value immediately, guards against a second start, and handles a failed sound:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
const startButton = document.querySelector("#startButton");
const countdownDisplay = document.querySelector("#countdown");
const finishSound = document.querySelector("#finishSound");

let remaining = 5;
let timeoutId = null;

function tick() {
  countdownDisplay.textContent = remaining;

  if (remaining === 0) {
    timeoutId = null;
    finishSound.currentTime = 0;
    finishSound.play().catch((error) => {
      console.error("Unable to play sound:", error);
    });
    startButton.disabled = false;
    return;
  }

  remaining -= 1;
  timeoutId = setTimeout(tick, 1000);
}

startButton.addEventListener("click", () => {
  if (timeoutId !== null) return;

  remaining = 5;
  startButton.disabled = true;
  tick();
});

This is a useful compact pattern, but a stored timeout handle and a separate running-state flag may be preferable if you add reset or cancellation. For a countdown that should reflect elapsed time reliably, use a deadline as in the fuller example.

Best Value
Amazon Basics USB-Powered Computer Speakers with Volume Control for Desktop or Laptop PC, Compact Size, Headphone Jack, Portable, Plug-N-Play, Black
  • USB-powered (5V) speakers plug directly into your computer for portable convenience
  • Turn the speakers on and adjust the volume using one simple control (located on the front of the speakers); volume control includes On/Standby
  • Simple plug-and-play setup (no drivers needed); can be used with headphones via the 3.5mm jack connector
  • Frequency range of 103 Hz - 20 KHz; 2.2 watts of total RMS power (1.1 watts per speaker)
  • Measures 2.76 by 3.55 by 5.3 inches (LxWxH); weighs approximately 1.4 pounds;

Legacy jQuery projects

jQuery is not required for this task. In an older project that already uses it, the click handler can still call ordinary JavaScript timer and audio APIs:

let timerId = null;
let remaining = 5;

$("#startButton").on("click", function () {
  if (timerId !== null) return;

  $(this).prop("disabled", true);
  $("#countdown").text(remaining);

  timerId = setInterval(function () {
    remaining -= 1;
    $("#countdown").text(remaining);

    if (remaining <= 0) {
      clearInterval(timerId);
      timerId = null;
      $("#startButton").prop("disabled", false);

      const audio = document.querySelector("#finishSound");
      audio.currentTime = 0;
      audio.play().catch(console.error);
    }
  }, 1000);
});

This compact legacy version decrements on callbacks, so it can drift if callbacks are delayed. For a longer or more timing-sensitive countdown, calculate the display from a deadline instead.

Accessibility and user experience

Use real buttons so the controls work with a keyboard, announce the changing countdown with a polite live region, and communicate completion in text as well as sound. Provide a reset or cancel action if users may need to stop the countdown. Do not make hearing the sound the only way to know the countdown finished: playback can be blocked, the device can be muted, or the user may not be able to hear it.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.