Home > front end >  Flickering occurs by using setInterval
Flickering occurs by using setInterval

Time:07-26

Below is my code, it shows normal at the beginning, however, as long as the number of fade out go to almost 20 times, then strong flickering occur, could anyone tell where it get wrong and how to fix it? Thanks.

function change() {
  let abc = document.getElementById("myDIV");
  abc.className = "mystyle";
  let aa = setInterval(function() {
    if (abc.className === "mystyle") {
      abc.className = "";
    }
  }, 1000);
  setTimeout(function() {
    clearInterval(aa)
  }, 1000);
  setInterval(change, 2000);
  return
}
.mystyle {
  background-color: coral;
  padding: 16px;
  opacity: 0;
  transition: opacity 1s linear;
}
<div id="myDIV">
  <p>I am myDIV.</p>
</div>
<p>Click the button to set a class for myDIV:</p>
<button onclick="change()">Try it</button>

CodePudding user response:

Here's another way to do it, closer to the original behaviour of your code, i.e. 1s with "mystyle" and 2s without:

<!DOCTYPE html>
<html>

<head>
  <style>
    .mystyle {
      background-color: coral;
      padding: 16px;
      opacity: 0;
      transition: opacity 1s linear;
    }
  </style>
</head>

<body>
  <div id="myDIV">
    <p>I am myDIV.</p>
  </div>
  <p>Click the button to set a class for myDIV:</p>
  <button onclick="change()">Try it</button>

  <script>
    function change() {
      let abc = document.getElementById("myDIV");
      abc.className = "mystyle";
      setTimeout(function() {
        let abc = document.getElementById("myDIV");
        abc.className = "";
      }, 1000);
      setTimeout(change, 2000);
      return
    }
  </script>
</body>

</html>

CodePudding user response:

I see far too many setTimeouts and setIntervals.

I think you wanted this?

const abc = document.getElementById("myDIV");
const toggle = () => abc.classList.toggle("mystyle");
const change = () => { toggle(); setInterval(toggle , 2000)};
.mystyle {
  background-color: coral;
  padding: 16px;
  opacity: 0;
  transition: opacity 1s linear;
}
<div id="myDIV">
  <p>I am myDIV.</p>
</div>
<p>Click the button to set a class for myDIV:</p>
<button onclick="change()">Try it</button>

  • Related