定时器
setInterval:间隔型
setTimeout:延时型
<body>
<input type="button" value="开启" id="btn1">
<input type="button" value="关闭" id="btn2">
<hr>
<ol>
<li>setInterval: 间隔型定时器</li>
<li>clearInterval(): 用于关闭间隔型定时器</li>
<li>setTimeout: 延时型定时器,只执行一次</li>
<li>clearTimeout(): 用于关闭延时型定时器</li>
<li>setInterval() 函数的返回值 timer 是定时器本身,可用作 clearInterval() 函数的参数</li>
</ol>
<script>
window.onload = function () {
var oBtn1 = document.getElementById('btn1');
var oBtn2 = document.getElementById('btn2');
var timer = null;
oBtn1.onclick = function () {
timer = setInterval(function () { //timer 的值为 setInterval() 的返回值
alert('Hello World!')
}, 5000)
console.log(timer)
}
oBtn2.onclick = function () {
clearInterval(timer) // setInterval() 的返回值可用于关闭定时器
}
}
</script>
</body>
Data对象
javascript"><script>
var time = new Date();
var year = time.getFullYear() //获取年份
var month = time.getMonth()+1 //获取月份(0-11)
var today = time.getDate() //获取日
var week = time.getDay() //获取周几
var hour = time.getHours() //获取小时
var minute = time.getMinutes() //获取分钟
var second = time.getSeconds() //获取秒
</script>
实例:数码时钟
<body>
<div id="div1"></div>
<script>
window.onload = function () {
//补0
function toDou(n) {
if (n < 10) {
return '0' + n
} else {
return n
}
}
function tick() {
var oDiv = document.getElementById('div1')
var oDate = new Date();
var str = toDou(oDate.getHours()) + ":" + toDou(oDate.getMinutes()) + ":" + toDou(oDate
.getSeconds());
oDiv.innerHTML = str
}
setInterval(tick, 1000)
tick() //为了解决1s间隔
}
</script>
</body>
实例:延时提示框
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
div {float: left; margin: 10px;}
#div1 {width: 100px; height: 100px; background: red;}
#div2 {width: 300px; height: 600px; background: #ccc; display: none;}
</style>
</head>
<body>
<div id="div1"></div>
<div id="div2"></div>
<script>
window.onload = function () {
var oDiv1 = document.getElementById('div1');
var oDiv2 = document.getElementById('div2');
var timer = null;
oDiv1.onmouseover = function () {
oDiv2.style.display = 'block'
clearTimeout(timer)
}
oDiv1.onmouseout = function () {
timer = setTimeout(function () {
oDiv2.style.display = 'none'
}, 500)
}
oDiv2.onmouseover = function () {
clearTimeout(timer)
}
oDiv2.onmouseout = function () {
timer = setTimeout(function () {
oDiv2.style.display = 'none'
}, 500)
}
}
//优化版
window.onload = function () {
var oDiv1 = document.getElementById('div1');
var oDiv2 = document.getElementById('div2');
var timer = null;
oDiv2.onmouseover = oDiv1.onmouseover = function () {
oDiv2.style.display = 'block'
clearTimeout(timer)
}
oDiv2.onmouseout = oDiv1.onmouseout = function () {
timer = setTimeout(function () {
oDiv2.style.display = 'none'
}, 500)
}
}
</script>
</body>