定时器在javascript中的作用
1、制作动画
2、异步操作
3、函数缓冲与节流
定时器类型及语法
/*
定时器:
setTimeout 只执行一次的定时器
clearTimeout 关闭只执行一次的定时器
setInterval 反复执行的定时器
clearInterval 关闭反复执行的定时器
*/
var time1 = setTimeout(myalert,2000);
var time2 = setInterval(myalert,2000);
/*
clearTimeout(time1);
clearInterval(time2);
*/
function myalert(){
alert('ok!');
}
定时器动画
<style type="text/css">
.box{
width: 100px;
height: 100px;
background-color: gold;
position: fixed;
left: 20px;
top: 20px;
}
</style>
<script type="text/javascript">
window.onload = function(){
var oBox = document.getElementById('box');
var left = 20;
//反复循环定时器,每30毫秒修改一次盒子的left值
var timer = setInterval(function(){
left += 2;
oBox.style.left = left + 'px';
//当left值大于700时停止动画(清除定时器)
if(left > 700){
clearInterval(timer);
}
},30);
}
</script>
</head>
<body>
<div class="box" id="box"></div>
</body>
定时器制作时钟
<script type="text/javascript">
window.onload = function(){
var oBox = document.getElementById('box');
function timeGo(){
var now = new Date();
// alert(now);//弹出美式时间:Wed Jun 20 2018 15:27:13 GMT+0800 (中国标准时间)
var year = now.getFullYear();//2018年
var month = now.getMonth() + 1;//6月弹出5//范围0-11
var date = now.getDate();//20号
var week = now.getDay();//3//星期几,西半球时间,范围0-6,星期日为一周的第一天,为0
var hour = now.getHours();
var minute = now.getMinutes();
var second = now.getSeconds();
// alert(hour + ":" + minute + ":" + second);//15:33:9
oBox.innerHTML = '当前时间是:' + year + '年' + toDouble(month) + '月' + toDouble(date) + '日 ' + toWeek(week) + ' ' + toDouble(hour) + ":" + toDouble(minute) + ":" + toDouble(second);
}
timeGo();
setInterval(timeGo, 1000);
}
//此函数将星期的数字转为汉字表示
function toWeek(num){
switch(num){
case 0:
return '星期天';
break;
case 1:
return '星期一';
break;
case 2:
return '星期二';
break;
case 3:
return '星期三';
break;
case 4:
return '星期四';
break;
case 5:
return '星期五';
break;
case 6:
return '星期六';
break;
}
}
//此函数将不足两位的数字前面补0
function toDouble(num){
if(num < 10){
return '0' + num;
}else{
return num;
}
}
</script>
网友评论