Функция clearInterval () не работает, не могу понять, почему ..? - PullRequest
1 голос
/ 14 марта 2020

Я пытаюсь выяснить, почему моя функция clearInterval() не работает. После многочисленных попыток исправить, попросить совет у Stack Overflow.

Кроме того, вместо того, чтобы функционировать как clearInterval(), он фактически ускоряется при нажатии кнопки «Стоп». Интересно, почему это ...?

TLDR: Создано несколько <div> квадратов, которые меняют цвет случайным образом. Используется интервальная функция для установки скорости смены цвета. Однако остановка функции не работает, а скорее ускоряет ее.

<!DOCTYPE html>
<html>

<head>

  <style>
    .squre {
      display: inline-block;
      width: 30px;
      height: 30px;
      border: 1px black solid;
    }
    
    button:hover {
      cursor: pointer;
    }
  </style>

</head>

<body>

  <div id='wrapper'>
    <div class='squre'></div>
    <div class='squre'></div>
    <div class='squre'></div>
    <div class='squre'></div>
    <div class='squre'></div>
    <div class='squre'></div>
    <div class='squre'></div>
    <div class='squre'></div>
  </div>

  <button onclick='interval()'>Change Color!</button>
  <button onclick='stopChange()' id='stop'>Stop This!</button>

  <script>
    function interval() {
      const mv = setInterval(colorChange, 100);
    }

    function stopChange() {
      clearInterval(mv);
    }

    function colorChange() {
      var cc = document.getElementsByClassName('squre');
      var ccStop = document.querySelector('#stop');
      var i;

      for (i = 0; i < 10; i++) {
        x = Math.floor(Math.random() * 11);
        if (x == 1) {
          cc[i].style.backgroundColor = 'red';
        } else if (x == 1) {
          cc[i].style.backgroundColor = 'orange';
        } else if (x == 2) {
          cc[i].style.backgroundColor = 'yellow';
        } else if (x == 3) {
          cc[i].style.backgroundColor = 'green';
        } else if (x == 4) {
          cc[i].style.backgroundColor = 'blue';
        } else if (x == 5) {
          cc[i].style.backgroundColor = 'purple';
        } else if (x == 6) {
          cc[i].style.backgroundColor = 'grey';
        } else if (x == 7) {
          cc[i].style.backgroundColor = 'black';
        } else if (x == 8) {
          cc[i].style.backgroundColor = 'green';
        } else if (x == 9) {
          cc[i].style.backgroundColor = 'white';
        } else if (x == 10) {
          cc[i].style.backgroundColor = 'brown';
        } else if (x == 0) {
          cc[i].style.backgroundColor = 'lightblue';
        } else {
          alert('error');
          break;
        }
      }
    }
  </script>
</body>

</html>

Ответы [ 2 ]

2 голосов
/ 14 марта 2020

сначала вы должны объявить mv вне функции, чтобы позволить другим функциям получать к ней доступ, вы устанавливаете ее как const var mv;

<!DOCTYPE html>
<html>

<head>

  <style>
    .squre {
      display: inline-block;
      width: 30px;
      height: 30px;
      border: 1px black solid;
    }
    
    button:hover {
      cursor: pointer;
    }
  </style>

</head>

<body>

  <div id='wrapper'>
    <div class='squre'></div>
    <div class='squre'></div>
    <div class='squre'></div>
    <div class='squre'></div>
    <div class='squre'></div>
    <div class='squre'></div>
    <div class='squre'></div>
    <div class='squre'></div>
    <div class='squre'></div>
    <div class='squre'></div>
    <div class='squre'></div>
  </div>

  <button onclick='interval()'>Change Color!</button>
  <button onclick='stopChange()' id='stop'>Stop This!</button>

  <script>
    var mv;

    function interval() {
      mv = setInterval(colorChange, 100);
    }

    function stopChange() {
      clearInterval(mv);
    }

    function colorChange() {
      var cc = document.getElementsByClassName('squre');
      var ccStop = document.querySelector('#stop');
      var i;

      for (i = 0; i < 10; i++) {
        x = Math.floor(Math.random() * 11);
        if (x == 1) {
          cc[i].style.backgroundColor = 'red';
        } else if (x == 1) {
          cc[i].style.backgroundColor = 'orange';
        } else if (x == 2) {
          cc[i].style.backgroundColor = 'yellow';
        } else if (x == 3) {
          cc[i].style.backgroundColor = 'green';
        } else if (x == 4) {
          cc[i].style.backgroundColor = 'blue';
        } else if (x == 5) {
          cc[i].style.backgroundColor = 'purple';
        } else if (x == 6) {
          cc[i].style.backgroundColor = 'grey';
        } else if (x == 7) {
          cc[i].style.backgroundColor = 'black';
        } else if (x == 8) {
          cc[i].style.backgroundColor = 'green';
        } else if (x == 9) {
          cc[i].style.backgroundColor = 'white';
        } else if (x == 10) {
          cc[i].style.backgroundColor = 'brown';
        } else if (x == 0) {
          cc[i].style.backgroundColor = 'lightblue';
        } else {
          alert('error');
          break;
        }
      }
    }
  </script>
</body>

</html>
2 голосов
/ 14 марта 2020

Вам нужно сделать mv глобальным. В противном случае переменная является только локальной, а значение недоступно за пределами функции.

var mv; // global, not const

function interval() {
    mv = setInterval(colorChange, 100);
}

function stopChange() {
    clearInterval(mv);
}
...