简体   繁体   中英

multiple javascript timers on 1 page

I hope you guys can help me out as I have little knowledge on javascripts. I've been using the same timer over and over again and it always works like a charm. Although when I'm trying to add the same timer again further down my page only 1 works.

 function startTimer(duration, display) { var timer = duration, minutes, seconds; setInterval(function () { minutes = parseInt(timer / 60, 10) seconds = parseInt(timer % 60, 10); minutes = minutes < 10 ? "0" + minutes : minutes; seconds = seconds < 10 ? "0" + seconds : seconds; display.textContent = minutes + ":" + seconds; if (--timer < 0) { timer = duration; } }, 1000); } window.onload = function () { var fiveMinutes = 60 * 10.1, display = document.querySelector('.time'); startTimer(fiveMinutes, display); }; 
 <span class="time">10:07</span> <br/> <br/> <br/> <span class="time">10:07</span> 

I have already tried adding a second script for a different class, but unfortunately no working results...

Is anyone able to help me out? JSfiddle prefered since I've little knowledge on javascript! Thanks in advance!

Use querySelectorAll

 function startTimer(duration, displays) { var timer = duration, minutes, seconds; setInterval(function () { minutes = parseInt(timer / 60, 10) seconds = parseInt(timer % 60, 10); minutes = minutes < 10 ? "0" + minutes : minutes; seconds = seconds < 10 ? "0" + seconds : seconds; Array.prototype.forEach.call(displays, function(display) { display.textContent = minutes + ":" + seconds; }); if (--timer < 0) { timer = duration; } }, 1000); } window.onload = function () { var fiveMinutes = 60 * 10.1, displays = document.querySelectorAll('.time'); startTimer(fiveMinutes, displays); }; 
 <span class="time">10:07</span> <br/> <br/> <br/> <span class="time">10:07</span> 

function startTimer(duration, display, display2) {
    var timer = duration, minutes, seconds;
    setInterval(function () {
        minutes = parseInt(timer / 60, 10)
        seconds = parseInt(timer % 60, 10);

        minutes = minutes < 10 ? "0" + minutes : minutes;
        seconds = seconds < 10 ? "0" + seconds : seconds;

        display.textContent = minutes + ":" + seconds;
        display2.textContent = display.textContent;
        if (--timer < 0) {
            timer = duration;
        }
    }, 1000);
}




 window.onload = function () {
    var fiveMinutes = 60 * 10.1,
        display = document.querySelector('.time');
        display2 = document.querySelector('.time2');
    startTimer(fiveMinutes, display ,display2);
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM