Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
426 views
in Technique[技术] by (71.8m points)

请教:js 页面有多个定时器,重置时间后显示冲突

问题描述

场景:
封装了一个 time 倒计时函数,通过数组循环出3个倒计时,
想点击按钮,重置其中一个时间

相关代码

html:

<div class="up">
    <div id="s1"></div>
    <div id="s2"></div>
    <div id="s3"></div>
    <div id="btn">重置时间</div>
</div>

js

var t;
    function time(timeCount,id){
        // clearInterval(t)
        t = window.setInterval(function(){
            var day = 0,
                hour = 0,
                min = 0,
                sec = 0;
            if(timeCount > 0){
                day = Math.floor(timeCount / (60 * 60 * 24));
                hour = Math.floor(timeCount / (60 * 60)) - (day * 24);
                min = Math.floor(timeCount / 60) - (day * 24 * 60) - (hour * 60);
                sec = Math.floor(timeCount) - (day * 24 * 60 * 60) - (hour * 60 * 60) - (min * 60);
            };
            if (min <= 9) min = '0' + min;
            if (sec <= 9) sec = '0' + sec;

            document.getElementById('s'+id).innerHTML = day+'天'+hour+'小时'+min+'分'+sec+'秒';
            timeCount--;
            if(timeCount < 0){
                document.getElementById('s'+id).innerHTML = '已结束';
            }
        }, 1000);
    };
    var dateArr = [{id: 1,time: 34535},{id: 2,time: 5533},{id: 3,time: 36538}]
    for (var i = 0; i < dateArr.length; i++) {
        time(dateArr[i].time,dateArr[i].id)
    }
    document.getElementById('btn').onclick = function(){
        time(60,1) // 修改第1个定时器时间为60秒
    }

// 页面显示:

0天9小时05分33秒 // 点击重置时间后,这里时间会重叠,重置前后的时间都会显示出来,交替显示

0天1小时02分13秒

0天9小时38分58秒

重置时间(按钮)

应该是清除定时器的错误,clearInterval(t),我注释掉了,如果执行的话页面只会显示最后一个倒计时,是哪里出现了错误,请教大家


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

加了clear也没用, t被多次覆盖了
image.png
大概这样


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...