Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading