计时器练习

1.获取当前时间的代码,时间显示在input窗口里边.

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta http-equiv="content-Type" charset="UTF-8">
    <meta http-equiv="x-ua-compatible" content="IE=edge">
    <title>Title</title>
</head>
<body>

<input type="text" id="i1">
<script>
    var i1Ele=document.getElementById('i1');
    var now=new Date();
    i1Ele.value=now.toLocaleString();
</script>
<!--获取当前时间的代码-->
</body>
</html>

 结果显示:

2.获取时间动起来的代码

一下代码实现了功能,但是存在bug:主要是点击两次开始,就不能停止时间了,思考是为什么?

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta http-equiv="content-Type" charset="UTF-8">
    <meta http-equiv="x-ua-compatible" content="IE=edge">
    <title>Title</title>
</head>
<body>

<input type="text" id="i1">
<button id="b1">开始</button>
<!--点击开始,就在input窗口里跑起时间,这里需要给按钮绑定一个事件-->
<button id="b2">停止</button>

<script>
    var i1Ele=document.getElementById('i1');
    var t;//定义一个t
    function f() {
        var now = new Date();
        i1Ele.value = now.toLocaleString();
    }
    // 升级,将上边两句话写在一个函数里边
    f();//默认需要先执行一遍,才会在input窗口里显示

    var b1Ele=document.getElementById('b1');
    b1Ele.onclick=function (ev) {
        t=setInterval(f,1000)
    };
    //找到按钮
    // 编写事件出发
    //定时,设置时间间隙.为1s

    var b2Ele=document.getElementById('b2');
    b2Ele.onclick=function (ev) {
        clearInterval(t)
    }
</script>
<!--获取当前时间的代码-->
</body>
</html>

 3.计时器完整改良版写法

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta http-equiv="content-Type" charset="UTF-8">
    <meta http-equiv="x-ua-compatible" content="IE=edge">
    <title>Title</title>
</head>
<body>

<input type="text" id="i1">
<button id="b1">开始</button>
<!--点击开始,就在input窗口里跑起时间,这里需要给按钮绑定一个事件-->
<button id="b2">停止</button>

<script>
    var i1Ele=document.getElementById('i1');
    var t;//定义一个t
    function f() {
        var now = new Date();
        i1Ele.value = now.toLocaleString();
    }
    // 升级,将上边两句话写在一个函数里边
    f();//默认需要先执行一遍,才会在input窗口里显示

    var b1Ele=document.getElementById('b1');
    //点开始,早这里点击了两次开始,意味着有两个定时任务,
    //clear是清除第二个,第一个已经被覆盖了,相当于找不回来了id不知道也就无法清除了.
    b1Ele.onclick=function (ev) {
        if(!t) {
            t = setInterval(f, 1000)
            // 通过判断t是否为空
        }
    };
    //找到按钮
    // 编写事件出发
    //定时,设置时间间隙.为1s

    var b2Ele=document.getElementById('b2');
    //点击停止
    b2Ele.onclick=function (ev) {
        clearInterval(t);   //根据id清除定时任务
        // console.log(t);
        t=null;
    }

</script>
<!--获取当前时间的代码-->
</body>
</html>
原文地址:https://www.cnblogs.com/studybrother/p/10386195.html