关于setInterval和clearInterval具体是干什么的这里就不详细介绍了,首先用setInterval写一个5秒后自动跳转到百度,而且每秒进行dom的更新,代码如下:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
</head>
<body>
<button id="bt">点击</button>
<p id = 'demo'></p>
<script>
var domBt = document.getElementById('bt')
var domP = document.getElementById('demo')
domBt.onclick = function(){
domBt.style.display = 'none'
setInterval(diaoyong,1000)
var time = 5
function diaoyong(){
if(time>0){
domP.innerHTML = time+''+'秒后跳转'
}else{
window.location.href = 'https://www.baidu.com'
}
time--
}
}
</script>
</body>
</html>
下面结合 setInterval和cleatInterval实现一个时钟的暂停和开始功能,代码如下:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>无标题文档</title>
</head>
<body>
<p>当前时间:</p>
<p id="demo"></p>
<button id="get">开始</button>
<button id="pause">暂停</button>
<script>
var domDemo = document.getElementById('demo')
var domGet = document.getElementById('get')
var domPause = document.getElementById('pause')
domGet.onclick = function(){
time = setInterval(function(){
var t = new Date()
var d = t.toLocaleTimeString()
domDemo.innerHTML = d
},1000)
}
domPause.onclick = function(){
clearInterval(time)
}
</script>
</body>
</html>
关于setTimeout和clearTimeout的功能类似就不说了。。。