Home > Enterprise >  How would I make this function repeat continuously?
How would I make this function repeat continuously?

Time:09-02

I'm making a small website and I'm trying to make two elements repeatedly hide and show so it'll look like it's switching between the two. I have a draft code that would do that but I'm not sure how to make it loop.

    function MyDraft(){
  var x = document.getElementById("one");
  var y = document.getElementById("two");
  if (y.style.display === "none"){
    x.style.display = "none";
    y.style.display = "block";
  }
  else {
    x.style.display = "block";
    y.style.display = "none";
  }
}

CodePudding user response:

If you use classes you can toggle an element having an hidden class (which sets visibility: hidden). Then just add the code that does the toggling for the elements inside setInterval.

// Cache the elements
const boxes = document.querySelectorAll('.box');

// Iterate over the elements toggling their
// `hidden` class
setInterval(() => {
  boxes.forEach(box => box.classList.toggle('hidden'));
}, 1000);
.box { width: 30px; height: 30px; background-color: lightgreen; }
.hidden { visibility: hidden; }
<div ></div>
<div ></div>

CodePudding user response:

Just use setInterval

    function MyDraft(){
  var x = document.getElementById("one");
  var y = document.getElementById("two");
  if (y.style.display === "none"){
    x.style.display = "none";
    y.style.display = "block";
  }
  else {
    x.style.display = "block";
    y.style.display = "none";
  }
}

var interval = setInterval(myDraft, [timeInMilliseconds]);

Save the interval variable somewhere so you can later call clearInterval if you want

  • Related