英文:
setTimeout javascript function 'detonator timer with delay'
问题
写一个 detonatorTimer(delay) 函数,每秒在控制台输出一个数字,从 delay(整数)开始,以 'Happy New Year!' 结束,而不是 0。通过 setTimeout 实现。代码中有错误,0 和文本会输出两次。
function detonatorTimer(delay) {
console.log(delay);
if (delay > 0) {
delay--;
setTimeout(detonatorTimer, 1000, delay);
}if(delay === 0) {
console.log('Happy New Year!');
}
}
detonatorTimer(3);
<details>
<summary>英文:</summary>
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);
</details>
# 答案1
**得分**: 0
你需要改进几个地方:
1. 有条件地记录 `delay`。
2. 使用 `else if` 而不是仅使用两个 `if`。
3. 在调用函数时移除 `console.log()`。
试试这个:
```javascript
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);
英文:
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:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
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);
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论