原生JS实现简易随机点名功能

定时器的工作原理,这里将用引用How JavaScript Timers Work中的例子来解释定时器的工作原理,该图为一个简单版的原理图。·

原文来自http://caibaojian.com/javascript-timer.html

上图中,左侧数字代表时间,单位毫秒;左侧文字代表某一个操作完成后,浏览器去询问当前队列中存在哪些正在等待执行的操作;蓝色方块表示正在执行的代码块;右侧文字代表在代码运行过程中,出现哪些异步事件。该图大致流程如下:

  • 程序开始时,有一个JS代码块开始执行,执行时长约为18ms,在执行过程中有3个异步事件触发,其中包括一个setTimeout、鼠标点击事件、setInterval
  • 第一个setTimeout先运行,延迟时间为10ms,稍后鼠标事件出现,浏览器在事件队列中插入点击的回调函数,稍后setInterval运行,10ms到达之后,setTimeout向事件队列中插入setTimeout的回调
  • 当第一个代码块执行完成后,浏览器查看队列中有哪些事件在等待,他取出排在队列最前面的代码来执行
  • 在浏览器处理鼠标点击回调时,setInterval再次检查到到达延迟时间,他将再次向事件队列中插入一个interval的回调,以后每隔指定的延迟时间之后都会向队列中插入一个回调
  • 后面浏览器将在执行完当前队头的代码之后,将再次取出目前队头的事件来执行

这里只是对定时器的原理做一个简单版的描述,实际的处理过程比这个复杂。

下面我们利用定时器实现一个简单的随机点名功能,代码如下:

<!DOCTYPE html>
<html lang="zh">
<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>
    <style>
        div{width: 300px;height: 100px;margin: 20px auto;font-size: 50px;text-align: center;line-height: 100px;}
        #btn{width: 200px;height: 40px;margin: 10px auto;background: red;color: #FFFFFF;font-size: 20px;text-align: center;cursor: pointer;display: block;}
    </style>
</head>
<body>
    <div id="content">请点击按钮</div>
    <input type="button" id="btn" value="开始">
    <script>
        var ocontent = document.getElementById("content");
        var obtn = document.getElementById("btn");
        var onoff = 1;        //打开
        var timer = null;        //设置全局变量
        var str = ["亚瑟","鬼谷子","铠","橘右京","项羽","梦奇","白起","赵云","李白","韩信","刘备","鲁班七号","墨子","孙膑","周瑜","庄周","廉颇","程咬金","典韦","后羿","扁鹊","李元芳","张飞","刘禅","兰陵王","达摩","曹操","钟馗","高渐离","宫本武藏","吕布","嬴政","姜子牙","老夫子","狄仁杰","夏侯惇","关羽","哪吒","太乙真人","干将莫邪","成吉思汗","牛魔","百里守约","百里玄策","苏烈","黄忠","诸葛亮","东皇太一","杨戬","后羿","孙悟空","张良","韩信","刘邦","达摩","马可波罗","娜可露露","露娜","妲己","甄姬","虞姬","大乔","小乔","王昭君","貂蝉","芈月","阿珂","花木兰","武则天","不知火舞","孙尚香","蔡文姬","安琪拉","钟无艳","女蜗","雅典娜","艾琳"]
        
        obtn.onclick = function(){
            if(onoff == 1){        //开始随机点名
                clearInterval(timer);//避免重复点击按钮出现bug
                timer = setInterval(function(){
                    var randomNum = Math.round(Math.random()*(str.length-1))
                    ocontent.innerHTML = str[randomNum];
                },10)
                onoff = 0;    //"定位"到暂停功能
                obtn.value = "就是你了"
            }else if(onoff == 0){
                clearInterval(timer);
                onoff = 1;    //暂停后需恢复到重新开始的功能
                obtn.value = "继续"
            }
        }
    </script>
</body>
</html>

效果截图如下:

这个随机点名功能实现起来相对容易,利用了定时器,设置了一个开关来控制开始和暂停。

另外我在另一篇随笔中用定时器写了一个倒计时功能,实现原理和这个类似,关键的两个点是定时器和开关,(相比较而言,开关更难理解)附上地址:https://www.cnblogs.com/qiaowanze/p/11399260.html

posted @ 2019-08-23 13:26  乔万泽  阅读(3246)  评论(0编辑  收藏  举报