1.setInterval与clearInterval
2.setTimeout与clearTimeout
setInterval:
<script>
setInterval(() => {
console.log("前端营地")
}, 1000)
</script>
clearInterval
<button>暂停</button>
<script>
let timer = setInterval(() => {
console.log("前端营地")
}, 1000)
let btn = document.querySelector('button')
btn.onclick = function () {
clearInterval(timer)
}
</script>
在网页中显示当前时间
<h1>12:00:00</h1>
<script>
let h1 = document.querySelector('h1')
setInterval(() => {
let timeNow = new Date();
let hours = timeNow.getHours()
let minutes = timeNow.getMinutes()
let seconds = timeNow.getSeconds()
let time = `${hours}:${minutes}:${seconds}`
h1.innerHTML = time
}, 500)
</script>