vendredi 25 juin 2021

Why do I get an Uncaught TypeError for my random numbers?

I get Uncaught TypeErrors while my script is running. I have some dark boxes that I want to be animated some time and then get rid of the animation again. I have realised it with an intervall. During the intervall the class of the elements will be changed and then the changes will be reversed. I coose the selected element by a randomly generated index. And this random number seems to be the root of the problem, but I can't figure out why or how to solve it.

Here is my minimal example:

let randomNumber;
let boxes = document.querySelectorAll(".dark");
let randomNumbers = [];
let milliseconds = 2000;
setInterval(function() {
  randomNumber = Math.ceil(Math.random() * boxes.length);
  randomNumbers.push(randomNumber);
  boxes[randomNumber].className = boxes[randomNumber].className.replace(/(?:^|\s)dark(?!\S)/g, " animated");
  setTimeout(function() {
    boxes[randomNumbers[0]].className = boxes[randomNumbers[0]].className.replace(/(?:^|\s)animated(?!\S)/g, " dark");
    randomNumbers.shift();
  }, boxes.length * milliseconds);
}, milliseconds);
@keyframes animated_background_color {
  0% {
    background-color: #e66000;
  }
  25% {
    background-color: #ff9500;
  }
  50% {
    background-color: #ffcb00;
  }
  75% {
    background-color: #ff9500;
  }
  100% {
    background-color: #e66000;
  }
}

.box {
  height: 20px;
  margin-bottom: 4px;
  width: 20px;
}

.dark {
  background-color: black;
}

.animated {
  animation-name: animated_background_color;
  animation-duration: 3s;
  animation-timing-function: linear;
  animation-iteration-count: infinite;
  background-color: #e66000;
}
<!DOCTYPE html>

<html>

<head>
  <title>Animation</title>
  <meta charset="UTF-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
</head>

<body>
  <div class="box dark"></div>
  <div class="box dark"></div>
  <div class="box dark"></div>
  <div class="box dark"></div>
  <div class="box dark"></div>
</body>

</html>



Aucun commentaire:

Enregistrer un commentaire