【问题标题】:How does this javascript timer using parseInt work?这个使用 parseInt 的 javascript 计时器是如何工作的?
【发布时间】:2021-02-27 23:56:46
【问题描述】:

我无法弄清楚这个常用的 javascript 计时器是如何工作的。所以我知道它使用 parseInt 和 timer 的值来导出分钟和秒,并使用 setInterval 每秒运行一次,每次更新值。我的问题是是什么导致计时器变量的值发生变化,从而产生倒计时的分钟和秒值。例如,第一次运行的分钟数是 1,秒数是 0。下一次运行的分钟数是 0,秒数是 59。下一次运行的秒数是 58,然后是 57 等等。值如何变化?我看没有递减。我在这里错过了什么?

function startTimer(duration, display) {
    var timer = duration, minutes, seconds;
    setInterval(function () {
        minutes = parseInt(timer / 60, 10);
        seconds = parseInt(timer % 60, 10);

        minutes = minutes < 10 ? "0" + minutes : minutes;
        seconds = seconds < 10 ? "0" + seconds : seconds;

        display.textContent = minutes + ":" + seconds;

        if (--timer < 0) {
            timer = duration;
        }
    }, 1000);
}

window.onload = function () {
    var fiveMinutes = 60 * 5,
        display = document.querySelector('#time');
    startTimer(fiveMinutes, display);
};

【问题讨论】:

  • parseInt(...) 读取一个字符串(希望有一个数值)并将其转换为一个数字,以便对其进行数学计算。如果字符串没有数字,则无法解析并抛出错误

标签: timer setinterval parseint


【解决方案1】:

在这里找到答案:https://forum.freecodecamp.org/t/timer-function-question/407582 它在 if 语句 if(--timer&lt;0) 中递减。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-18
    • 1970-01-01
    • 1970-01-01
    • 2011-03-02
    • 1970-01-01
    • 2013-09-20
    相关资源
    最近更新 更多