间歇函数
定时器函数
1.开启定时器
//语法:setInterval(函数,间隔时间)
//每隔一段事件调用这个函数
//间隔时间单位是毫秒
2.关闭定时器
//语法:let 变量名 = setInterval(函数,间隔时间)
//clearInterval(变量名)
//注意:函数名字不用加括号
//定时器返回的是一个id数字
/一般不会刚创建就停止,而是满足一定条件再停止
<body>
<button>倒计时10s</button>
<script>
// 添加定时器的语法setInterval(function(){},时间)
// 间隔时间毫秒做单位
// setInterval(function(){
// //不会停止 类似死循环
// console.log('123');
// },1000)
// // 获取元素
// let btn = document.querySelector('button')
// // 设置总时长
// let time = 10
// // 点击事件
// btn.addEventListener('click', function () {
// // 开启定时器
// // timeId:
// let timeId = setInterval(function () {
// time--
// btn.innerText = `倒计时${time}s`
// btn.disabled = true
// // 判断事件是否到0,到0停止,清除定时器
// if (time === -1) {
// // 清除定时器
// clearInterval(timeId)
// btn.disabled = false
// btn.innerText = '你想干啥'
// }
// }, 1000)
// })
// 关闭定时器,在事件里面定义
// let 变量名 = setInterval(函数,间隔时间)
// clearInterval(变量名)
// 满足条件才会停止
// 获取元素
let btn = document.querySelector('button')
// 点击事件
btn.addEventListener('click', function () {
let time = 10
// 开启定时器
let times = setInterval(function () {
time--
btn.innerText = `还剩${time}s`
btn.disabled = true
// 判断
if (time == -1) {
btn.disabled = false
// 清除定时器
clearInterval(times)
btn.innerText = '你瞅啥'
}
}, 1000)
})
</script>
</body>
//自动切换图片
<head>
<style>
* {
padding: 0;
margin: 0;
}
div {
width: 700px;
height: 320px;
margin: 100px auto;
position: relative;
}
p {
position: absolute;
left: 0;
bottom: 0;
line-height: 50px;
background-color: #666;
color: #fff;
width: 100%;
padding-left: 10px;
font-size: 20px;
box-sizing: border-box;
}
</style>
</head>
<body>
<div>
//比如
<img src="./images/b01.jpg" alt="" />
<p>第1张图片</p>
</div>
<script>
// 获取变量
let img = document.querySelector('img')//设置src属性
let p = document.querySelector('p')//图片描述
let i = 1 //索引
let times
// 全局索引1~9
// 添加定时器
// 根据索引生成路径,给img的src属性
// 封装一个定时器函数
function timeId() {
times = setInterval(function () {
// 索引自增
i++
// 判断两个或三个=号
if (i == 10) {
// 赋值一个=号
i = 1
}
// 生成索引成路径
img.src = `./images/b0${i}.jpg`
// 图片描述
p.innerText = `第${i}张图片`
}, 1800)
}
// 调用开启定时器
timeId()
// 鼠标进入事件
let div = document.querySelector('div')
div.addEventListener('mouseenter', function () {
// 关闭定时器
clearInterval(times)
})
// 鼠标移出
div.addEventListener('mouseleave', function () {
// 开启定时器
console.log(timeId());
})
</script>
</body>