javascript - 倒数计时器JS的问题 - IF条件

标签 javascript html counter countdown

我是 JavaScript 和这个网站的新手。

我有以下用于事件计时器倒计时的代码:

https://codepen.io/iraffleslowd/pen/povGNdo

我的问题确实是 if 条件。

setInterval(function () {
    if (distance < 0) {
        clearInterval(x);
        document.getElementById("demo").innerHTML = "EXPIRED";
    }
}, 1000);

由于我的事件在倒计时结束时不会过期,因此事件会在开始后大约一小时结束。

有人可以帮我添加另一个条件,以便在该时间间隔内不显示 Expired,而是显示 Live 或类似的内容吗?

非常感谢!

最佳答案

您想要管理 3 个不同的状态...

  1. 直播倒计时
  2. 直播
  3. 已过期
(() => {

    const intervalId = setInterval(() => {

        // update countdown timer

        if (distance < -(ELAPSED_GAMETIME_IN_MS)) {
            // set EXPIRED
            clearInterval(intervalId);
        }
        else if (distance < 0) {
            // set LIVE
        }

    }, 1000);

})();

编辑 工作示例 此示例使用了 moment,因为它是一个很棒的实用程序,可以提供日期的所有必要数学和格式,并且非常适合此场景。

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <meta http-equiv="X-UA-Compatible" content="ie=edge" />
        <title>Document</title>
    </head>
    <body>
        <div id="countdown"></div>

        <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.js"></script>
        <script>
            (() => {
                const countdownEl = document.getElementById("countdown");

                const START_DATE = moment("2020-01-22");
                const ELAPSED_GAMETIME_IN_MS = 1000 * 60 * 60 * 2; // 2 hours in milliseconds
                const intervalId = setInterval(() => {
                    const TIME_FROM_START = START_DATE.diff(moment());

                    countdownEl.innerHTML = START_DATE.fromNow(); // This could be modified to show different levels of granularity...

                    if (TIME_FROM_START < -ELAPSED_GAMETIME_IN_MS) {
                        countdownEl.innerHTML = "EXPIRED";
                        clearInterval(intervalId);
                    } else if (TIME_FROM_START < 0) {
                        countdownEl.innerHTML = "LIVE";
                    }
                }, 1000);
            })();
        </script>
    </body>
</html>

关于javascript - 倒数计时器JS的问题 - IF条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59870072/

相关文章:

c++ - 计算间隔中数字频率的有效算法

javascript - AngularJS如何在多个ajax请求成功后调用函数?

jquery - Bootstrap 3 中的加载状态按钮

php - 变量在函数外不可见

CSS:为什么图像在 Chrome 中稍微向下移动?

Latex: 第 n 页 for\frontmatter 和第 n 页 for\mainmatter

function - Scala 调用函数时递增计数器

javascript - 如何在 NET MVC 3 Razor 中仅触发 JavaScript 函数而无需 Controller 处理请求

javascript - 什么时候*不*使用内置的新作品?

javascript - 如何在原始 JavaScript 中遍历 dom 元素?