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:
- Log the
delay
conditionally - Use
else if
instead of just twoif
s - 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);