微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

某些操作后 SetInterval 无法正常工作

如何解决某些操作后 SetInterval 无法正常工作

当我按下开始按钮时它会运行

function startGame() {
        invaderId = setInterval(moveInvaders,1000);
    }

在我的游戏中,它每秒从上到下移动块。我还有一个激光可以射击和摧毁方块。当您按空格键时,它会使用另一个

laserId = setInterval(moveLaser,100)

在你按下空格键之前,方块每秒移动得很好,但在使用激光方块之后,移动速度比 1 秒快。 如果我在 StartGame 函数之外设置 IngresserId = setInterval(moveInvaders,1000) 一切都很好。但是我需要按开始按钮后才能开始游戏。

也许更容易看到这一点。所以,我在这里留下完整的代码,有人可以解释为什么会发生

const resultdisplay = document.querySelector('#result');
let width = 15;
let BOARD_SIZE = width * width 
let currentShooterIndex = 202;
let currentInvaderIndex = 0;
let alienInvadersTakenDown = [];
let result = 0;
let direction = 1;
let invaderId

const $board = document.querySelector('.grid')
for(let i = 0; i < BOARD_SIZE; i++) {
    $board.appendChild(document.createElement('div'))
}
const squares = document.querySelectorAll('.grid div');
//define alien invaders
const alienInvaders = [0,1,2,3,4,5,6];

//=======draw the aliens invaders========
alienInvaders.forEach(invader => squares[currentInvaderIndex + invader].classList.add('invader'));

//=======draw the shooter================
squares[currentShooterIndex].classList.add('shooter');

//==========move shooter along the line=========
function moveShooter (e) {
    squares[currentShooterIndex].classList.remove('shooter');
    switch (e.keyCode) {
        case 37:
            if(currentShooterIndex % width !== 0) {
                currentShooterIndex -=1;
                break;
            }
        case 39:
            if(currentShooterIndex % width < width -1) {
                currentShooterIndex +=1;
                break;
            }
    }
    squares[currentShooterIndex].classList.add('shooter');
}

//=============move the alien invaders===============
function moveInvaders() {
    const leftEdge = alienInvaders[0] % width === 0;
    const rightEdge = alienInvaders[alienInvaders.length - 1] % width === width - 1;

    //=====decide next direction for aliens invaders=======
    if ((leftEdge && direction === -1) || (rightEdge && direction === 1)) {
        direction = width;
    } else if (direction === width) {
        if (leftEdge) direction = 1;
        else  direction = -1;
    }

    //=====remove invaders from prevIoUs position===========
    for (let i = 0; i <= alienInvaders.length - 1; i++) {
        squares[alienInvaders[i]].classList.remove('invader');
    }

    //===========change invaders position due to direction======
    for (let i = 0; i <= alienInvaders.length - 1; i++) {
        alienInvaders[i] += direction;
    }

    //============show current invaders===========
    for (let i = 0; i <= alienInvaders.length - 1; i++) {
        if (!alienInvadersTakenDown.includes(i)) {
            squares[alienInvaders[i]].classList.add('invader');
        }
    }

    //==========decide a game over=============
    if (squares[currentShooterIndex].classList.contains('invader','shooter')) {
        resultdisplay.textContent = "Game Over";
        squares[currentShooterIndex].classList.add('boom');
        clearInterval(invaderId);
        document.removeEventListener('keydown',moveShooter);
        document.removeEventListener('keyup',shoot);
    }
    for (let i = 0; i <= alienInvaders.length - 1; i++) {
        if (alienInvaders[i] > (squares.length - (width - 1))) {
            resultdisplay.textContent = "Game Over";
            clearInterval(invaderId);
        }
    }

    //==========decide a win===========
    if (alienInvadersTakenDown.length === alienInvaders.length) {
        resultdisplay.textContent = "You Win!";
        clearInterval(invaderId);
    }
}//moveInvaders



//=======shoot at aliens function========
function shoot(e) {
    let laserId;
    let currentLaserIndex = currentShooterIndex;
    //move the laser from shooter to the alien invader
    function moveLaser() {
        squares[currentLaserIndex].classList.remove('laser');
        currentLaserIndex -= width;
        squares[currentLaserIndex].classList.add('laser');
        if (squares[currentLaserIndex].classList.contains('invader')) {
            squares[currentLaserIndex].classList.remove('laser');
            squares[currentLaserIndex].classList.remove('invader');
            squares[currentLaserIndex].classList.add('boom');
            setTimeout(() => squares[currentLaserIndex].classList.remove('boom'),250);
            clearInterval(laserId);
            //==============add to alien takedown array killed invader using currentlaser index
            const alienTakeDown = alienInvaders.indexOf(currentLaserIndex);
            alienInvadersTakenDown.push(alienTakeDown);
            result++;
            resultdisplay.textContent = result;
        }
        if (currentLaserIndex < width) {
            clearInterval(laserId);
            setTimeout(() => squares[currentLaserIndex].classList.remove('laser'),100);
        }
    }
    //========define "space" - shoot button and run laser function=======
    switch (e.keyCode) {
        case 32:
            laserId = setInterval(moveLaser,100);
            break;
    }
}


// invaderId = setInterval(moveInvaders,speedInterval);



// setTimeout(() => invaderId = setInterval(moveInvaders,speedInterval),2000)



document.addEventListener('keydown',moveShooter);
document.addEventListener('keyup',shoot);

function startGame() {
    invaderId = setInterval(moveInvaders,1000);
}
.grid {
    display: flex;
    flex-wrap: wrap;
    border: 3px solid #1b63d0;
    width: 300px;
    height: 300px;
}

.grid div {
    width: 20px;
    height: 20px;
}

.shooter {
    background-color: blue;
}

.invader {
    background-color: purple;
}

.boom {
    background-color: red;
}

.laser {
    background-color: orange;
}
<!doctype html>
<html lang="en">
<head>
    <Meta charset="UTF-8">
    <Meta name="viewport"
          content="width=device-width,user-scalable=no,initial-scale=1.0,maximum-scale=1.0,minimum-scale=1.0">
    <Meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <div class="container">
        <div class="wrap">
            <div class="grid"></div>
            <div class="control-block">
                <button class="start-btn" onclick="startGame()">Start</button>
                <div class="score">score: <span id="result">0</span></div>

                <div class="control-btn">
                    <img src="left.png">
                </div>
                <div class="control-btn">
                    <img src="right.png">
                </div>
                <div class="control-btn">
                    <img src="space.png">
                </div>
                <!-- <div><img src="right.png"></div>
                <div><img src="space.png"></div> -->
            </div>
        </div>
    </div>

    <script src="script.js"></script>

</body>
</html>

解决方法

尝试在 event.target.blur() 函数中添加 startGame

为什么??因为当你点击开始按钮时。它实际上是聚焦的,当你点击空间时,它的浏览器默认属性是点击聚焦的元素。因此,您必须将焦点从按钮上移开。

const resultDisplay = document.querySelector('#result');
let width = 15;
let BOARD_SIZE = width * width 
let currentShooterIndex = 202;
let currentInvaderIndex = 0;
let alienInvadersTakenDown = [];
let result = 0;
let direction = 1;
let invaderId

const $board = document.querySelector('.grid')
for(let i = 0; i < BOARD_SIZE; i++) {
    $board.appendChild(document.createElement('div'))
}
const squares = document.querySelectorAll('.grid div');
//define alien invaders
const alienInvaders = [0,1,2,3,4,5,6];

//=======draw the aliens invaders========
alienInvaders.forEach(invader => squares[currentInvaderIndex + invader].classList.add('invader'));

//=======draw the shooter================
squares[currentShooterIndex].classList.add('shooter');

//==========move shooter along the line=========
function moveShooter (e) {
    squares[currentShooterIndex].classList.remove('shooter');
    switch (e.keyCode) {
        case 37:
            if(currentShooterIndex % width !== 0) {
                currentShooterIndex -=1;
                break;
            }
        case 39:
            if(currentShooterIndex % width < width -1) {
                currentShooterIndex +=1;
                break;
            }
    }
    squares[currentShooterIndex].classList.add('shooter');
}

//=============move the alien invaders===============
function moveInvaders() {
    const leftEdge = alienInvaders[0] % width === 0;
    const rightEdge = alienInvaders[alienInvaders.length - 1] % width === width - 1;

    //=====decide next direction for aliens invaders=======
    if ((leftEdge && direction === -1) || (rightEdge && direction === 1)) {
        direction = width;
    } else if (direction === width) {
        if (leftEdge) direction = 1;
        else  direction = -1;
    }

    //=====remove invaders from previous position===========
    for (let i = 0; i <= alienInvaders.length - 1; i++) {
        squares[alienInvaders[i]].classList.remove('invader');
    }

    //===========change invaders position due to direction======
    for (let i = 0; i <= alienInvaders.length - 1; i++) {
        alienInvaders[i] += direction;
    }

    //============show current invaders===========
    for (let i = 0; i <= alienInvaders.length - 1; i++) {
        if (!alienInvadersTakenDown.includes(i)) {
            squares[alienInvaders[i]].classList.add('invader');
        }
    }

    //==========decide a game over=============
    if (squares[currentShooterIndex].classList.contains('invader','shooter')) {
        resultDisplay.textContent = "Game Over";
        squares[currentShooterIndex].classList.add('boom');
        clearInterval(invaderId);
        document.removeEventListener('keydown',moveShooter);
        document.removeEventListener('keyup',shoot);
    }
    for (let i = 0; i <= alienInvaders.length - 1; i++) {
        if (alienInvaders[i] > (squares.length - (width - 1))) {
            resultDisplay.textContent = "Game Over";
            clearInterval(invaderId);
        }
    }

    //==========decide a win===========
    if (alienInvadersTakenDown.length === alienInvaders.length) {
        resultDisplay.textContent = "You Win!";
        clearInterval(invaderId);
    }
}//moveInvaders



//=======shoot at aliens function========
function shoot(e) {
    let laserId;
    let currentLaserIndex = currentShooterIndex;
    //move the laser from shooter to the alien invader
    function moveLaser() {
        squares[currentLaserIndex].classList.remove('laser');
        currentLaserIndex -= width;
        squares[currentLaserIndex].classList.add('laser');
        if (squares[currentLaserIndex].classList.contains('invader')) {
            squares[currentLaserIndex].classList.remove('laser');
            squares[currentLaserIndex].classList.remove('invader');
            squares[currentLaserIndex].classList.add('boom');
            setTimeout(() => squares[currentLaserIndex].classList.remove('boom'),250);
            clearInterval(laserId);
            //==============add to alien takedown array killed invader using currentlaser index
            const alienTakeDown = alienInvaders.indexOf(currentLaserIndex);
            alienInvadersTakenDown.push(alienTakeDown);
            result++;
            resultDisplay.textContent = result;
        }
        if (currentLaserIndex < width) {
            clearInterval(laserId);
            setTimeout(() => squares[currentLaserIndex].classList.remove('laser'),100);
        }
    }
    //========define "space" - shoot button and run laser function=======
    switch (e.keyCode) {
        case 32:
            laserId = setInterval(moveLaser,100);
            break;
    }
}


// invaderId = setInterval(moveInvaders,speedInterval);



// setTimeout(() => invaderId = setInterval(moveInvaders,speedInterval),2000)



document.addEventListener('keydown',moveShooter);
document.addEventListener('keyup',shoot);

function startGame() {
    event.target.blur();
    invaderId = setInterval(moveInvaders,1000);
}
.grid {
    display: flex;
    flex-wrap: wrap;
    border: 3px solid #1b63d0;
    width: 300px;
    height: 300px;
}

.grid div {
    width: 20px;
    height: 20px;
}

.shooter {
    background-color: blue;
}

.invader {
    background-color: purple;
}

.boom {
    background-color: red;
}

.laser {
    background-color: orange;
}
<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width,user-scalable=no,initial-scale=1.0,maximum-scale=1.0,minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <div class="container">
        <div class="wrap">
            <div class="grid"></div>
            <div class="control-block">
                <button class="start-btn" onclick="startGame()">Start</button>
                <div class="score">Score: <span id="result">0</span></div>

                <div class="control-btn">
                    <img src="left.png">
                </div>
                <div class="control-btn">
                    <img src="right.png">
                </div>
                <div class="control-btn">
                    <img src="space.png">
                </div>
                <!-- <div><img src="right.png"></div>
                <div><img src="space.png"></div> -->
            </div>
        </div>
    </div>

    <script src="script.js"></script>

</body>
</html>

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。