1. 程式人生 > >定時器,setInterval、clearInterval

定時器,setInterval、clearInterval

clas color scrip defined NPU ext func ntb tex

<!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>

定時器,setInterval、clearInterval