windows对象提供的两种定时器的应用,时钟

来源:互联网 发布:网络打字兼职可信吗 编辑:程序博客网 时间:2024/06/05 21:11

周期性定时器

每隔指定的时间间隔,执行一次指定的功能

var timer1 = window.setInterval(task,  time);

设置一个周期性定时器,并立即启动它;先计时,再运行。

window.clearInterval( timer1 );

停止并删除计时器

一次性定时器

间隔指定的时间后,执行一次指定的功能,仅执行一次。

var timer2 = window.setTimeout(task,  time);

设置一个一次性计时器,并立即启动它;先计时,再执行。

window.clearTimeout( timer2 );

在一次性计时器执行之前打断并删除该计时器。

以下代码在网页中实现一个时钟:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"> <head>  <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/>  <title></title>  <style type="text/css">    *{margin:0; padding:0;}    #clock{        width: 300px;        height: 300px;        margin: 0 auto;        border: 1px solid #aaa;        border-radius: 50%;        position: relative;    }    .p{        position: absolute;        left: 150px;        transform-origin: left center;    }    .hour{        width: 60px;        height: 12px;        background: #faa;        top: 144px;    }    .minute{        width: 120px;        height: 8px;        background: #aaf;        top: 146px;    }    .second{        width: 150px;        height: 4px;        background: #afa;        top: 148px;    }  </style> </head> <body>  <div id="clock">    <div class="p hour"></div>    <div class="p minute"></div>    <div class="p second"></div>  </div>  <script>  function drawClock(){    var now = new Date();    var h = now.getHours() % 12;    var m = now.getMinutes();    var s = now.getSeconds();    var hpointer = document.getElementsByClassName('hour')[0];    hpointer.style.transform = 'rotate('+(h*30-90)+'deg)';    var mpointer = document.getElementsByClassName('minute')[0];    mpointer.style.transform = 'rotate('+(m*6-90)+'deg)';    var spointer = document.getElementsByClassName('second')[0];    spointer.style.transform = 'rotate('+(s*6-90)+'deg)';  }  drawClock();  window.setInterval(drawClock, 1000);  </script> </body></html>

时钟

0 0