-1

How can we repeatedly update the contents of a div using setInterval

I am using the question from this link as a reference How to repeatedly update the contents of a <div> by only using JavaScript?

but i have got few questions here

  1. Can we do it without anonymous functions,using closures. I have tried but could not end up with any workable solution.
  2. How can we make it run infinitely, with the following code it gets stopped once i reaches 10.

window.onload = function() {
  var timing = document.getElementById("timer");
  var i = 0;
  var interval = setInterval(function() {
    timing.innerHTML = i++;
    if (i > 10) {
      clearInterval(interval);
      i = 0;
      return;
    }
  }, 1000);
}
<div id="timer"></div>

I am confused about setIntervals and closures can some one help me here

Thanks

Community
  • 1
  • 1
Geeky
  • 7,420
  • 2
  • 24
  • 50
  • 2
    "with the following code it gets stopped once i reaches 10" --- because you're stopping it explicitly with the `clearInterval`. If you don't want to stop it - just don't – zerkms Oct 19 '16 at 01:55
  • Not sure why there are down votes here.I was honestly confused with setIntervals – Geeky Oct 19 '16 at 03:54

2 Answers2

1

You could do something like this with a closure. Just reset your i value so, you will always be within your given range.

window.onload = function() {

  var updateContent = (function(idx) {

    return function() {

      if (idx === 10) {
        idx = 0;
      }

      var timing = document.getElementById("timer");
      timing.innerHTML = idx++;
    }
  })(0);

  var interval = setInterval(updateContent, 1000);

}
<div id="timer"></div>
Sreekanth
  • 3,110
  • 10
  • 22
  • I think you're confusing "closure" with "IIFE". I see no reason for the latter here. Also, if you're going to go to all the trouble of using an IIFE, why are you retrieving the DOM element each time through the loop? –  Oct 19 '16 at 04:27
1

This one should be clearer.

function updateTimer() {
  var timer = document.getElementById("timer");
  var timerValue = parseInt(timer.getAttribute("data-timer-value")) + 1;
  if (timerValue == 10) {
    timerValue = 0;
  }
  timer.setAttribute("data-timer-value", timerValue);
  timer.innerHTML = "the time is " + timerValue;
}
window.onload = function() {
  setInterval(updateTimer, 1000);
}
<div id="timer" data-timer-value="0"></div>
Eric
  • 11
  • 5
  • The only problem with this approach is the variable could be anytime modified from the attributes and it no longer works as it intended. Also, it doesn't involve a Closure as OP asked for. – Sreekanth Oct 19 '16 at 04:05
  • @Eric..Thanks for the solution.I want it to display 0 to 9 continously .Here it is incrementing – Geeky Oct 19 '16 at 04:48
  • I edited the code sample, now it goes from 0 to 9 over and over – Eric Oct 19 '16 at 13:00