【问题标题】:I can't get the setInterval function to work我无法让 setInterval 函数工作
【发布时间】:2019-01-22 05:08:12
【问题描述】:

我正在尝试制作一个西蒙说游戏,我需要每秒随机更改背景。它会改变,但它会立即完成所有操作。我计划稍后添加一个样式表,但现在,我只需要它来工作。请帮忙。我是初学者,所以请温柔。

HTML:

<!DOCTYPE HTML>
<html>
    <head>
        <title>Simon Says</title>
        <script src="script.js"></script>
    </head>

    <body>
        <button onclick="blue()" class="blue">Blue</button> 
        <button onclick="green()" class="green">Green</button>
        <button onclick="red()" class="red">Red</button>        
        <button onclick="yellow()" class="yellow">Yellow</button>
        <button onclick="ready()" class="ready">Ready</button>
    </body>
</html>

Javascript:

var seq = [0,1,2,1,3,2];
var rnd; 

function ready(){
    rnd = seq.length + 1;
    for(i = 0; i <= rnd;){
        seq[rnd] = Math.floor(Math.random()*4);
        setInterval(
        function () {
            switch(seq[i]){
                case 0:
                    document.body.style.backgroundColor = "rgb(0,0,255)";
                break;

                case 1:
                    document.body.style.backgroundColor = "rgb(0,255,0)";
                break;

                case 2:
                    document.body.style.backgroundColor = "rgb(255,0,0)";
                break;

                case 3:
                    document.body.style.backgroundColor = "rgb(255,255,0)";
                break;
            }
        }, 1000);
        console.log(i);
        i++;
    }
    rnd++;
}

【问题讨论】:

标签: javascript html


【解决方案1】:

setInterval 并不是你真正想要的。尝试另一种方法 -

const buttons =
  { red: document.querySelector('.red')
  , green: document.querySelector('.green')
  , blue: document.querySelector('.blue')
  , yellow: document.querySelector('.yellow')
  }
  
const sleep = ms =>
  new Promise (r => setTimeout (r, ms))

const playSequence = async (seq, speed = 500) =>
{ for (const s of seq)
  { buttons[s].classList.toggle('lit', true)  
    await sleep (speed)
    buttons[s].classList.toggle('lit', false)
    await sleep (speed)
  }
}

playSequence ([ 'red', 'red', 'blue', 'green', 'yellow', 'red' ])
  .then(_ => console.log('done'))
.red { --rgb: 255, 0, 0; }
.green { --rgb: 0, 255, 0; }
.blue { --rgb: 0, 0, 255; }
.yellow { --rgb: 255, 255, 0; }


button {
  display: inline-block;
  width: 10vw;
  height: 10vw;
  background-color: rgba(var(--rgb), 0.25);
}

button.lit {
  background-color: rgba(var(--rgb), 1);
}
<button class="red"></button>
<button class="green"></button>
<button class="blue"></button>
<button class="yellow"></button>

调整speed增加难度-

// 200 ms delay
playSequence ([ 'red', 'red', 'blue', 'green', 'yellow', 'red' ], 200)
  .then(_ => console.log('done'))

展开下面的 sn-p 可以看到它播放得更快 -

const buttons =
  { red: document.querySelector('.red')
  , green: document.querySelector('.green')
  , blue: document.querySelector('.blue')
  , yellow: document.querySelector('.yellow')
  }
  
const sleep = ms =>
  new Promise (r => setTimeout (r, ms))

const playSequence = async (seq, speed = 500) =>
{ for (const s of seq)
  { buttons[s].classList.toggle('lit', true)  
    await sleep (speed)
    buttons[s].classList.toggle('lit', false)
    await sleep (speed)
  }
}

// 200 ms delay
playSequence ([ 'red', 'red', 'blue', 'green', 'yellow', 'red' ], 200)
  .then(_ => console.log('done'))
.red { --rgb: 255, 0, 0; }
.green { --rgb: 0, 255, 0; }
.blue { --rgb: 0, 0, 255; }
.yellow { --rgb: 255, 255, 0; }


button {
  display: inline-block;
  width: 10vw;
  height: 10vw;
  background-color: rgba(var(--rgb), 0.25);
}

button.lit {
  background-color: rgba(var(--rgb), 1);
}
<button class="red"></button>
<button class="green"></button>
<button class="blue"></button>
<button class="yellow"></button>

【讨论】:

    【解决方案2】:

    您可以使您的代码更干燥,并解决循环/计时器问题,只需将颜色添加到数组并将主体背景设置为由随机索引给出的该数组的索引。而不是setInterval,我使用了setTimeout,它调用一个函数,直到完成步骤数。

    // Cache the DOM elements
    const out = document.querySelector('#out');
    const { body } = document;
    
    const seq = [0, 1, 2, 1, 3, 2];
    
    // Set up your color array
    const cols = ["rgb(0,0,255)", "rgb(0,255,0)", "rgb(255,0,0)", "rgb(255,255,0)"];
    
    function ready() {
    
      // `next` accepts a parameter c which is the current
      // step count. It's default is 0
      const next = function(c = 0) {
    
        // If the step count is less than 6
        if (c < 6) {
    
          // Update the DOM...
          out.textContent = `Step: ${c + 1}`;
          body.style.backgroundColor = cols[seq[c]];
    
          // ...and call the function again after a second
          // incrementing the step count
          setTimeout(next, 1000, ++c);
        }
      }
    
      // Call the loop the first time
      next();
    }
    #out { background-color: white };
    <button onclick="ready()" class="ready">Ready</button>
    <div id="out"></div>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-08-31
      • 1970-01-01
      • 2020-12-10
      • 1970-01-01
      • 2021-02-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多