zoukankan      html  css  js  c++  java
  • js多个计时器互不影响触发

    前段时间有个要实现发短信互不影响的倒计时效果,但是没有实现,就换成了另一种方式,可是心里总是放不下,就问了朋友,结果没想到这么简单……

    以下是实现的demo,关于语法的讲解,以及原理在注释中都有提到,有需要的可以根据自己的具体需求来做改动:

    <!DOCTYPE html>
    <html>
        <head>
            <meta charset="utf-8">
            <title></title>
        </head>
        <body>
            <button class="time" type="button">点击倒计时</button><br><br>
            <button class="time" type="button">点击倒计时</button><br><br>
            <button class="time" type="button">点击倒计时</button><br><br>
            <button class="time" type="button">点击倒计时</button><br><br>
            <button class="time" type="button">点击倒计时</button><br><br>
            <button class="time" type="button">点击倒计时</button><br><br>
        </body>
        <script type="text/javascript">
        /** document.querySelectorAll()与getElementsByClassName一样,返回NodeList集合
        *   NodeList集合不是一个数组, 用不了数组的forEach方法
            可以用css的方法选取元素
            Array.prototype.forEach.call()
            Array.prototype.forEach.call(a, function)  等于 a.forEach(function)
            (这是因为Nodelist集合并不是一个真正的数组,用不了数组的方法,只能用这种方法使用, 或者把他转换成数组在使用
    )
    
        */
            Array.prototype.forEach.call(document.querySelectorAll('.time'), function (value, key, arr) {
                // 初始化属性
                value.isDown = false;
                value.onclick = function () {
                    // 当属性为false时进入倒计时方法,同时isDown变为true
                    if (!this.isDown) {
                        // 定时器和剩余的时间和定时器绑定到调用他的内阁元素身上
                        this.time = 5;
                        this.isDown = true;
                        startTime(this)
                    }
                }
            })
            function startTime(ob) {
                ob.innerHTML = '(' + ob.time + ')';
                // setInterval(Expression,DelayTime)设置循环事件
                ob.timeer = setInterval(function () {
                    ob.time -= 1;
                    if (ob.time === 0) {
                        // 倒计时为0时清除循环事件
                        clearInterval(ob.timeer);
                        // 状态属性变为false
                        ob.isDown = false;
                        ob.innerHTML = '倒计时完毕,点击再次倒计时';
                    } else {
                        ob.innerHTML = '(' + ob.time + ')';
                    }
                }, 1000)
            }
        </script>
    </html>

    以上是整理的朋友的代码,有问题的朋友也可以共同探讨

  • 相关阅读:
    Express 2015 RC for Windows 10 安装
    离线下载Express 2015 for Windows 10
    离线下载Express 2015 for Windows 10
    windows 10预览版升级win10 7月29 10240.16384
    windows 10预览版升级win10 7月29 10240.16384
    C# 获得系统环境
    C# 获得系统环境
    C++宽字符串转字符串
    C++宽字符串转字符串
    C++ md5类,封装好
  • 原文地址:https://www.cnblogs.com/wangfengzhu/p/6297520.html
Copyright © 2011-2022 走看看