setTimeout javascript function 'detonator timer with delay'

Write a function detonatorTimer(delay) that outputs a number to the console every second, starting with delay (integer) and ending with ‘Happy New Year!’ instead of 0. By setTimeout. There are errors in the code, 0 and the text is output twice.

function detonatorTimer(delay) {
    console.log(delay);
        if (delay > 0) {
            delay --;
            setTimeout(detonatorTimer, 1000, delay);
        }if(delay === 0) {
            console.log('Happy New Year!');
        }
    }

detonatorTimer(3);

>Solution :

You need to improve a couple of things:

  1. Log the delay conditionally
  2. Use else if instead of just two ifs
  3. Remove the console.log() when invoking the function.

Try with this one:

function detonatorTimer(delay) {
        if (delay > 0) {
          console.log(delay);
          delay --;
          setTimeout(detonatorTimer, 1000, delay);
        } else if(delay === 0) {
          console.log('Happy New Year!');
        }
    }
detonatorTimer(3);

Leave a Reply