Play sound when timer reaches zero

How can I prevent the timer looping when it runs out - it should stay at zero but it jumps back round to two minutes again - and how can I play a soundfile when the countdown timer reaches a certain number.

Ideally I’d like to have a 5, 4, 3, 2, 1 voice countdown when the timer reaches 5.

<script type="text/javascript">
    function startTimer(duration, display) {
        var timer = duration, minutes, seconds;
            setInterval(function () {
            minutes = parseInt(timer / 60, 10);
            seconds = parseInt(timer % 60, 10);

            minutes = minutes < 10 ? "0" + minutes : minutes;
            seconds = seconds < 10 ? "0" + seconds : seconds;

            display.textContent = minutes + ":" + seconds;

            if (--timer < 0) {
                timer = duration;
        }, 1000);

    window.onload = function () {
        var twoMinutes = 60 * 2,
        display = document.querySelector('#time');
        startTimer(twoMinutes, display);


Use setTimeout instead of setInterval. It’s the same logic, but runs only once.

You can’t. Common browsers require user action to play sound in order not to annoy their users by unwanted noise.

Thank you.

It is required for a web game I am developing that is intended to be played among a small group on a local server.

The code snippet from soundmanager2 html5 example - JSFiddle - Code Playground appears to acheive a similar result with an audio file but I have tried to incorporate the audio portion of the code into my existing countdown script but cannot get it to work as it does on the pen.

You start the counter on window load. Have a look at the console of your browser. There will probably be an error message. Playing sound requires user action like a button press.
Your fiddle example uses a button. That might be the crucial difference.

Ah ok. Understood.

Thank you. Is it possible to switch the countdown script o use button instead of the window onload?

I’m not sure if you can delay the user action like this in a browser like Chrome or Safari as they actively interrupt calls to play without user action. So not sure if the button click can be delegated only in the fiddle or elsewhere also, you’ll have to try.
Not sure if I understand your question correctly: Instead of the window load you could create a button and put an event listener on it that calls the function like

btn.addEventListener('click', () => startTimer(twoMinutes, display))