js小功能--定时器&时钟的实现

定时器的实现

setInterval(function,time) //开启定时器,执行多次
setimeout(function,time) //开启定时器,只执行一次
clearInterval(timer) //关闭setInterval 定时器

具体实现代码如下:

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档title>
<script>
window.onload=function(){
    var oBtnOn=document.getElementById("on");
    var oBtnOff=document.getElementById("off");
    oBtnOn.onclick=function(){
        timer=setInterval(function(){
        alert('haha...');
        },1000);
    }
    oBtnOff.onclick=function(){
        clearInterval(timer);
        }
}
script>
head>
<body>
<input id="on" type="button" value="O N"/>
<input id="off" type="button" value="OFF"/>
body>
html>

完整版小时钟:

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档title>
<script>
function checkTime(i)
    {
    if (i<10) 
      {return "0" + i;}
      else{return ""+i;}
    }
window.onload=function (){
    var oImg=document.getElementsByTagName("img");
    function tick(){
        var date=new Date();
        var h=date.getHours();
        var m=date.getMinutes();
        var s=date.getSeconds();

        var srt=checkTime(h)+checkTime(m)+checkTime(s);
        for(i=0;i//oImg[i].src='img/'+srt[i]+'.png'}//由于兼容性问题,改为以下语句
        oImg[i].src='img/'+srt.charAt(i)+'.png'}
    }
    setInterval(tick,1000);
    tick();//减少延迟
}
script>
head>

<body style="background:black;font-size:50px;color:white">
<img src="img/0.png" />
<img src="img/0.png" />
:
<img src="img/0.png" />
<img src="img/0.png" />
:
<img src="img/0.png" />
<img src="img/0.png" />
body>
html>

这里存在一个小问题,当根据索引取字符串的时候,可能出现不兼容的问题,具体情况及解决方法如下;

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档title>
<script>
    window.onload=function(){
        var str="iovjdf";
        alert(str[3]);//在 chrome IE8及以上都正常运行,但是以下就失败不兼容
        //兼容的写法
        alert(str.charAt(3));//所有浏览器都兼容
    }
script>
head>
<body>
body>
html>

你可能感兴趣的:(javaScript)