循环 switch 语句 Javascript

Loop a switch statement Javascript

嘿,这是我的第一个 post,我正在尝试重新创建 google 恐龙游戏,但是当我打开页面时,会选择一个随机动画,但只有一次我需要一种方法来循环它不断让我们每秒说一次。 “kubbur”是原版游戏中的仙人掌。

var kubbur = document.getElementById("kubbur");
var kubbur2 = document.getElementById("kubburTwo");
var kubbur3 = document.getElementById("kubburThree");
var randomKubbur = Math.floor(Math.random() * 3); //chooses a random number

switch(randomKubbur) {
    case 0:
            if(kubbur.classList !="animateKubbur1"){
            kubbur.classList.add ("animateKubbur1");
            }
            setTimeout(function(){
            kubbur.classList.remove("animateKubbur1");
            }, 1000)

        break;
    case 1:
            if(kubbur2.classList !="animateKubburTwo"){
            kubbur2.classList.add ("animateKubburTwo");
            }
            setTimeout(function(){
            kubbur2.classList.remove("animateKubburTwo");
            }, 1000)
        break;
    case 2:
            if(kubbur3.classList !="animateKubburThree"){
            kubbur3.classList.add ("animateKubburThree");
            }
            setTimeout(function(){
            kubbur3.classList.remove("animateKubburThree");
            }, 1000)
        break;

}

var kubburs = document.querySelectorAll(".kubbur");

// Create a function
function animate() {
  var classes      = ['animateKubbur1', 'animateKubburTwo', 'animateKubburThree'],
      randomKubbur = Math.floor(Math.random() * 3), // random number between 0-2
      elem         = kubburs[randomKubbur],
      className    = classes[randomKubbur];
      
  elem.classList.add(className);
  setTimeout(function() {
    elem.classList.remove(className);
  }, 1000);
  
  // Repeat it after 700-1200 ms
  setTimeout(animate, Math.random() * (1200 - 700) + 700);
}

// Call it
animate();
.kubbur { width: 50px; height: 50px; background: #ccc; display: inline-block; }
.animateKubbur1 { background: red; }
.animateKubburTwo { background: green; }
.animateKubburThree { background: blue; }
<div class="kubbur"></div>
<div class="kubbur"></div>
<div class="kubbur"></div>