定时器,setInterval、clearInterval

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        #id1{
            width: 200px;
            height: 50px;
        }
    </style>
</head>
<body>
<input type="text" id="id1" onclick="begin()"><!--事件 onclick-->
<button onclick="end()">
    停止
</button>
<script>
    function showTime() {
        var current_time=new Date().toLocaleString();//拿到当前时间且以字符串显示
        var ele=document.getElementById("id1");//拿到input的id
        ele.value=current_time;//当前时间显示在input的value中

    }
    var clock1;
    function begin() {
        if (clock1==undefined){//如果clock1==undefined
            showTime();//显示时间
            clock1 = setInterval(showTime,1000);//1秒显示一次
        }
    }

    function end() {
        clearInterval(clock1);//停止clock1
        clock1=undefined;//赋值
    }
</script>
</body>
</html>

猜你喜欢

转载自www.cnblogs.com/wfl9310/p/9195575.html