0

I have a js script that makes a countdown getting the div's data-attrib. My problem is that I've many div in the same page where I would like to see each one own count down. I tried to use a for loop to iterate every tag but something wrong.

var x = document.getElementsByClassName("countdown_ele");
var i;

for (i = 0; i < x.length; i++) {
  var seconds = x[i].dataset.timer;

  function timer() {
    var days = Math.floor(seconds / 24 / 3600);
    var hoursLeft = Math.floor((seconds) - (days * 86400));
    var hours = Math.floor(hoursLeft / 3600);
    var minutesLeft = Math.floor((hoursLeft) - (hours * 3600));
    var minutes = Math.floor(minutesLeft / 60);
    var remainingSeconds = seconds % 60;

    function pad(n) {
      return (n < 10 ? "0" + n : n);
    }
    x[i].innerHTML = pad(days) + ":" + pad(hours) + ":" + pad(minutes) + ":" + +pad(remainingSeconds);
    if (seconds == 0) {
      clearInterval(countdownTimer);
      x[i].innerHTML = "Completed";
    } else {
      seconds--;
    }
  }
  var countdownTimer = setInterval('timer()', 1000);
}
<div class="countdown_ele" data-timer="30"></div>
mplungjan
  • 169,008
  • 28
  • 173
  • 236
cco
  • 33
  • 5
  • What **exactly** do you mean by "something wrong"? What is not working with the given code? What have you tried to make it work? – Nico Haase Mar 01 '21 at 08:21
  • You are defining a function _inside_ a loop. Meaning, if you loop 10 times, you will re-create (overwrite) this function 10 times over itself. And inside this function, you define another function, which will also be overriden 10 times. – Jeremy Thille Mar 01 '21 at 08:34
  • 1
    Here is a version of your script without closure issues https://jsfiddle.net/mplungjan/sjd2kazq/ – mplungjan Mar 01 '21 at 08:48
  • 1
    Thank you all guys. JeremyThille I've understood :) @mplungjan your solution is perfect!! Thanks so much! – cco Mar 01 '21 at 10:28

0 Answers0