Search code examples
javascriptsettimeoutsetintervalreload

how to loop a display using setTimeout, setInterval or?


codepens below showing use of setTimeout, setInterval & location.reload what other options are available?

next level I want is - add a control to allow the user to cycle forwards/backwards easily.

codepen using setTimeout & location.reload (requires reloading page - want to avoid this) https://codepen.io/GuruAtWork/pen/PoPYbKK

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>title</title>
  </head>
  <body>
    <div id="info">start</div>
    <script>
      var elem = document.getElementById("info");
      setTimeout(function () {
        elem.innerHTML = "one";
      }, 1000);
      setTimeout(function () {
        elem.innerHTML = "two";
      }, 2000);
      setTimeout(function () {
        elem.innerHTML = "three";
      }, 3000);
      setTimeout(function(){
         //window.location.reload(1);
         location.reload()
      }, 4000);
    </script>
  </body>
</html>

codepen using setInterval nested inside setTimeout https://codepen.io/GuruAtWork/pen/rNOBjBa

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>title</title>
  </head>
  <body>
    <div id="info">start</div>
    <script>
      var elem = document.getElementById("info");
      setTimeout(function () {
         console.log("setTimeout 1000")
         elem.innerHTML = "setTimeout 1000";
         setInterval(function () {
           elem.innerHTML = "setInterval one";
           console.log("setInterval 1000")
         }, 4000);
      }, 1000);
      setTimeout(function () {
         console.log("setTimeout 2000")
         elem.innerHTML = "setTimeout 2000";
         setInterval(function () {
           console.log("setInterval 2000")
           elem.innerHTML = "setInterval two";
         }, 4000);
      }, 2000);
      setTimeout(function () {
         console.log("setTimeout 3000")
         elem.innerHTML = "setTimeout 3000";
         setInterval(function () {
           console.log("setInterval 3000")
           elem.innerHTML = "setInterval three";
         }, 4000);
      }, 3000);

    </script>
  </body>
</html>


Solution

  • You can use an array to store the contents, and loop the index. To go back/forward just change the value of i and update.

    var contents=["one", "two", "three"], i = 0;
    setInterval(function() {
      document.getElementById("content").innerHTML = contents[i];
      if (++i >= 3) i = 0;
    }, 1000);
    <div id='content'></div>