开启定时器
setInterval 间隔型 无线循环执行下去
setTimeout 延时型 只执行一次
<script> function show() { alert('a'); } setInterval(show, 1000);//无线循环执行下去 </script> <script> function show() { alert('a'); } setTimeout(show, 1000);//只执行一次 </script>
停止定时器
clearInterval 清除setInterval开启的定时器
clearTimeout 清除setTimeout开的的定时器
开启清除定时器小例子
<!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>无标题文档</title> <script> window.onload=function () { var oBtn1=document.getElementById('btn1'); var oBtn2=document.getElementById('btn2'); var timer=null; oBtn1.onclick=function () { timer=setInterval(function (){ alert('a'); }, 1000); }; oBtn2.onclick=function () { clearInterval(timer); }; }; </script> </head> <body> <input id="btn1" type="button" value="开启" /> <input id="btn2" type="button" value="关闭" /> </body> </html>
获取系统时间
Date对象
getHours 时
getMinutes 分
getSeconds 秒
getFullYear() 年
getMonth() 月
getDate() 日
getDay() 星期
<script>
var oDate=new Date();//创建日期对象
//alert(oDate.getFullYear()); 获取当天年份
//alert(oDate.getMonth()+1); 获取月份 月份要加一
//alert(oDate.getDate()); 获取日
//alert(oDate.getDay()); 获取星期 0 1 2 3 4 5 6 0对应的是周日 其他一一对应
</script>
效果思路
获取系统时间 Date对象
getHours、getMinutes、getSeconds 显示系统时间
字符串连接
空位补零
设置图片路径 charAt方法
<!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>无标题文档</title> <script> function toDou(n) { if(n<10) { return '0'+n;//判断是否小于10 如果小于在前面加0,把一个数字给他补0变成两位数例如05 } else { return ''+n;//前面加空格让其返回字符串 } } window.onload=function () { var aImg=document.getElementsByTagName('img'); function tick(){ var oDate=new Date(); var str=toDou(oDate.getHours())+toDou(oDate.getMinutes())+toDou(oDate.getSeconds()); for(var i=0;i<aImg.length;i++) { aImg[i].src='img/'+str.charAt(i)+'.png';//设置图片路径 charAt方法 获取字符串上的某一位东西 让其兼容ie } } setInterval(tick, 1000); tick(); }; </script> </head> <body style="background:black; color: white; font-size:50px;"> <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>