我写了一个轮播图,其中上一张和下一张都绑定了清除定时器,自动每点一次就清除掉上次使用定时器以防止他不规则的自动翻图片,但是没起到作用
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.outer {
width: 640px;
margin: 50px auto;
text-align: center;
}
</style>
<script>
window.onload = function () {
// 图片轮播
const info = document.getElementById("info")
const prev = document.getElementById("prev")
const auto = document.getElementById("auto")
const next = document.getElementById("next")
const btnwrapper = prev.parentNode
const imgwrapper = btnwrapper.previousElementSibling
const imgchange = document.getElementById("imgchange")
// alert(imgchange)
const imgArr = ["./images/1.png", "./images/2.png", "./images/3.png", "./images/4.png", "./images/5.png"]
let temp = 0
info.textContent = `总共 ${imgArr.length} 张图片,当前 ${temp + 1} 张`
let timer
auto.addEventListener("click", function(){
//关闭
clearTimeout(timer)
timer = setTimeout(function fn(){
temp++
if(temp > 4){
temp = 0
}
imgchange.src=imgArr[temp]
info.textContent = `总共 ${imgArr.length} 张图片,当前 ${temp + 1} 张`
setTimeout(fn,3000)
},3000)
})
prev.addEventListener("click", function () {
clearTimeout(timer)
temp--
if(temp < 0){
temp = 4
}
imgchange.src=imgArr[temp]
info.textContent = `总共 ${imgArr.length} 张图片,当前 ${temp + 1} 张`
})
next.addEventListener("click", function () {
clearTimeout(timer)
temp++
if(temp > 4){
temp = 0
}
imgchange.src=imgArr[temp]
info.textContent = `总共 ${imgArr.length} 张图片,当前 ${temp + 1} 张`
})
// next.onclick = function(){
// imgchange.src=imgArr[temp++]
// }
}
</script>
</head>
<body>
<div class="outer">
<p id="info">
总共n张图片,当前m张
</p>
<div class="img-wrapper">
<img id="imgchange" src="./images/1.png" alt="这是一张图片">
</div>
<div class="btn-wrapper">
<button id="prev">上一张</button>
<button id="auto">自动</button>
<button id="next">下一张</button>
</div>
</div>
</body>
</html>
希望各位能帮忙看一下!!十分感谢!