同一页面创建多个定时器

  • Post author:
  • Post category:其他


在一个网页中同时创建多个定时器实现不同任务的倒计时功能,定时器倒计时时间到达之后需要将定时器清除,否则就会新创建的定时器就会受到干扰,代码如下,

<style>
.card-container {
    width: 100px;
    height: 150px;
    background-color: antiquewhite;
    box-shadow: 1px 2px 5px #b1b1b1;
    margin-right: 20px;
}
.tanchuang {
    width: 50px;
    height: 80px;
    background-color: aqua;
}
</style>


<ul style="display: flex;list-style: none;">
    <li id="card0" class="card-container"></li>
    <li id="card1" class="card-container"></li>
    <li id="card2" class="card-container"></li>
</ul>
// 判断是否存在同名弹窗并删除
function ifSameTanchaung(index) {
    if (tanchuangArr.length > 0) {
        for (let j = 0; j < tanchuangArr.length; j++) {
            if (tanchuangArr[j] == `tanchuang${index}`) {
                deleteSameTanchaung(tanchuangArr[j], `tanchuang${j}`, j)
            }
        }
    }
}

// 直接删除同名弹窗
function deleteSameTanchaung(timer, idName, index) {
    clearInterval(timer)
    let tanchuangItem = document.getElementById(idName)
    tanchuangItem.parentNode.removeChild(tanchuangItem)
        // deleteTimer(index)
}

let timerArr = []
// 倒计时4s定时器
function timeCoutDown(timer, idName, index, fn) {
    let Time = 4
    timer = setInterval(() => {
        if (Time <= 0) {
            clearInterval(timer)
            let tanchuangItem = document.getElementById(idName)
            tanchuangItem.parentNode.removeChild(tanchuangItem)
                deleteTimer(index)
            }
            else {
                fn(Time--)
            }
     }, 1000)
         timerArr.push(timer)
}

// 删除数组中的某个弹窗和对应的定时器
function deleteTimer(index) {
    tanchuangArr.splice(index, 1)
    timerArr.splice(index, 1)
}


let tanchuangArr = []
// 触发弹窗函数(websocket)
function tanchuang() {
    let i = 1
    ifSameTanchaung(i)
    tanchuangArr.push(`tanchuang${i}`)
    let cardItem = document.getElementById(`card${i}`)
    let tanchuang = document.createElement('div')
    tanchuang.id = `tanchuang${i}`
    tanchuang.classList.add('tanchuang')
    cardItem.appendChild(tanchuang)
    timeCoutDown(tanchuangArr[i], `tanchuang${i}`, i)
}

tanchuang()

setTimeout(() => {
    tanchuang()
}, 3000);



版权声明:本文为MengHuanLanSe原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。