简体   繁体   English

我无法使用setInterval函数

[英]I can't get the setInterval function to work

I'm trying to make a simon says game and i need the background to change randomly every second. 我正在尝试制作Simon说的游戏,并且我需要每秒随机更改背景。 It changes, but the it does everything at once. 它会发生变化,但是会立即执行所有操作。 I'm planning on adding a stylesheet later on, but for now, I just need this to work. 我打算稍后再添加样式表,但是现在,我只需要使用它即可。 Please help. 请帮忙。 I'm a beginner, so please be gentle. 我是初学者,请保持温柔。

HTML: 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: 使用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++;
}

setInterval is not really what you want here. setInterval并不是您真正想要的。 Try an alternative approach - 尝试另一种方法-

 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> 

Adjust the speed to increase difficulty - 调整speed以增加难度-

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

Expand the snippet below to see it play faster - 展开下面的代码片段,以查看其播放速度更快-

 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> 

You can make your code more DRY, and resolve the loop/timer issue, by simply adding the colours to an array and setting the body background to the index of that array given by the random index. 您可以使代码更干燥,只需将颜色添加到数组中,然后将主体背景设置为随机索引所给定的该数组的索引,即可解决循环/计时器问题。 Instead of setInterval I've used setTimeout which calls a function until the number of steps has been completed. 我使用setTimeout代替setInterval ,它会调用一个函数,直到完成步骤数为止。

 // 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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM