JavaScript 中的 `setTimeout` 函数用于设定延迟后触发的定时器。

huangapple go评论60阅读模式
英文:

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 &#39;Happy New Year!&#39; 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:

  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:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

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

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年2月14日 20:23:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/75447779.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定