Home > Web Front-end > JS Tutorial > How to implement a simple countdown effect of hours, minutes and seconds in js (code example)

How to implement a simple countdown effect of hours, minutes and seconds in js (code example)

青灯夜游
Release: 2018-10-23 18:00:47
forward
5505 people have browsed it

The content of this article is to introduce how to implement a simple countdown effect of hours, minutes and seconds in js (code example). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Effect:

How to implement a simple countdown effect of hours, minutes and seconds in js (code example)

##javascript:

    <script type="text/javascript">
        function countTime() {
            //获取当前时间
            var date = new Date();
            var now = date.getTime();
            //设置截止时间
            var endDate = new Date("2018-10-25 00:00:00");
            var end = endDate.getTime();
            //时间差
            var differTime = end - now;
            //定义变量,h,m,s保存倒计时的时间
            var h, m, s;
            if (differTime >= 0) {
                h = Math.floor(differTime / 1000 / 60 / 60);
                m = Math.floor(differTime / 1000 / 60 % 60);
                s = Math.floor(differTime / 1000 % 60);
                h = h < 10 ? ("0" + h) : h;
                m = m < 10 ? ("0" + m) : m;
                s = s < 10 ? ("0" + s) : s;
                document.getElementById("_h").innerHTML = h + "时";
                document.getElementById("_m").innerHTML = m + "分";
                document.getElementById("_s").innerHTML = s + "秒";
                setTimeout(countTime, 1000);

            } else {
                document.getElementById("_h").innerHTML = "00时";
                document.getElementById("_m").innerHTML = "00分";
                document.getElementById("_s").innerHTML = "00秒";
            }


        }
    </script>
Copy after login

HTML:

<body onload="countTime()">
    <p class="timer">
        <span id="_h"></span>
        <span id="_m"></span>
        <span id="_s"></span>
    </p>
</body>
Copy after login

The above is the detailed content of How to implement a simple countdown effect of hours, minutes and seconds in js (code example). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:cnblogs.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template