Остановка работающей javascript функции - PullRequest
1 голос
/ 08 марта 2020

Я создаю приложение, в котором пользователь должен нажимать на красный фон, чтобы набрать очки. Конечная цель - создать игру типа «крот». Я создал функцию, чтобы красный фон появлялся с интервалом в 1 секунду, а счет увеличивался всякий раз, когда я щелкаю и применяю класс везде, где есть красный фоновый класс. Однако у меня возникают проблемы с остановкой работы selectBox () и selectBox () с counter.inner HTML === '00: 10: 01 '.

Может кто-нибудь сказать мне, где я не прав?

const box = document.querySelectorAll('.box');
const startBtn = document.querySelector('#start');
const roachBox = document.querySelector('.roach-box');
const score = document.querySelector('#score');
const stopwatch = document.querySelector('#stopwatch');
const winnerText = document.querySelector('.winner-text');
const playAgainBtn = document.querySelector('#play-again');
const boxArray = Array.from(box);
let newClass = null;

startBtn.addEventListener('click', startGame);

function startGame() {
    setInterval(selectBox, 1000);
    addScore();
    begin();
    setInterval(checkScore);
    startBtn.classList.add('hide');
}

function selectBox() {
    if (newClass) newClass.classList.toggle('red');
    let randomNum = Math.floor(Math.random() * 6);
    let randomClass = boxArray[randomNum];
    randomClass.classList.add('red');
    newClass = randomClass;
}

roachBox.addEventListener('click', function(e) {
    Array.from(boxArray).forEach((e) => e.classList.remove('match'));

    e.target.classList.add('match');
});

function addScore() {
    roachBox.addEventListener('click', function(e) {
        if (e.target.classList.contains('red') && e.target.classList.contains('match')) {
            score.innerHTML = parseInt(score.innerHTML, 10) + 1;
        }
    });
}

let ms = 0,
    s = 0,
    m = 0;
let timer;

function begin() {
    timer = setInterval(run, 10);
}

function run() {
    counter.textContent = (m < 10 ? '0' + m : m) + ': ' + (s < 10 ? '0' + s : s) + ': ' + (ms < 10 ? '0' + ms : ms);
    ms++;
    if (ms == 100) {
        ms = 0;
        s++;
    }
    if (s == 60) {
        s = 0;
        m++;
    }
}

function checkScore() {
    let scoreInnerText = score.innerText;
    if (counter.innerHTML === '00: 10: 01' && +scoreInnerText >= 5) {
        winnerText.innerHTML = 'Wohooo! You are the king of roach killing!';
        playAgainBtn.classList.remove('hide');
    } else if (counter.innerHTML === '00: 10: 01' && +scoreInnerText < 5) {
        winnerText.innerHTML = 'Uhoh this does not seem to be your strong suit :(';
        playAgainBtn.classList.remove('hide');
    }
}

playAgainBtn.addEventListener('click', playAgain);

function playAgain() {
    window.location.reload();
}

Ответы [ 2 ]

1 голос
/ 08 марта 2020

Это просто из списка интервалов. Вы можете вызвать onEndGame () в checkScore () или нажать кнопку «Завершить игру»

const box = document.querySelectorAll('.box');
const startBtn = document.querySelector('#start');
const endGameBtn = document.querySelector('#end-game');
const roachBox = document.querySelector('.roach-box');
const score = document.querySelector('#score');
const stopwatch = document.querySelector('#stopwatch');
const winnerText = document.querySelector('.winner-text');
const playAgainBtn = document.querySelector('#play-again');
const boxArray = Array.from(box);
let newClass = null;
let selectBoxClear = null;
let scoreClear = null;
let timer = null;

startBtn.addEventListener('click', startGame);
endGameBtn.addEventListener('click', onEndGame);

// You can call this function on run time
function onEndGame(){
  window.clearInterval(selectBoxClear);
  window.clearInterval(scoreClear);
  window.clearInterval(timer);
  
  checkScore();
  playAgainBtn.classList.remove('hide');
}

function startGame() {
	selectBoxClear = setInterval(selectBox, 1000);
	addScore();
	begin();
	scoreClear = setInterval(checkScore);
	startBtn.classList.add('hide');
	counter.classList.remove('hide');
}

function selectBox() {
	if (newClass) newClass.classList.toggle('red');
	let randomNum = Math.floor(Math.random() * 6);
	let randomClass = boxArray[randomNum];
	randomClass.classList.add('red');
	newClass = randomClass;
	roach();
}

roachBox.addEventListener('click', function(e) {
	Array.from(boxArray).forEach((e) => e.classList.remove('match'));

	e.target.classList.add('match');
	slap();
});

function addScore() {
	roachBox.addEventListener('click', function(e) {
		if (e.target.classList.contains('red') && e.target.classList.contains('match')) {
			score.innerHTML = parseInt(score.innerHTML, 10) + 1;
		}
	});
}

let ms = 0,
	s = 0,
	m = 0;

function begin() {
	timer = setInterval(run, 10);
}

function run() {
	counter.textContent = (m < 10 ? '0' + m : m) + ': ' + (s < 10 ? '0' + s : s) + ': ' + (ms < 10 ? '0' + ms : ms);
	ms++;
	if (ms == 100) {
		ms = 0;
		s++;
	}
	if (s == 60) {
		s = 0;
		m++;
	}
}

function checkScore() {
	let scoreInnerText = score.innerText;
	if (counter.innerHTML === '00: 10: 01' && +scoreInnerText >= 5) {
		winnerText.innerHTML = 'Wohooo! You are the king of roach killing!';
		playAgainBtn.classList.remove('hide');
        onEndGame();
	} else if (counter.innerHTML === '00: 10: 01' && +scoreInnerText < 5) {
		winnerText.innerHTML = 'Uhoh this does not seem to be your strong suit :(';
		playAgainBtn.classList.remove('hide');
        onEndGame();
	} 
}

playAgainBtn.addEventListener('click', playAgain);

function playAgain() {
	window.location.reload();
}

function roach() {
	const roach = document.querySelector('#roach');
	roach.play();
}

function slap() {
	const slap = document.querySelector('#slap');
	slap.play();
}
.box {
	height: 200px;
}

.red {
	background-image: url(https://www.procareservices.co.nz/wp-content/uploads/2017/08/cockroach-square.jpg);
	background-size: contain;
	background-repeat: no-repeat;
}

.match {
	background-color: white;
}

.hide {
	display: none;
}

.roach-box {
	background-color: white;
}

.roach-box {
	cursor: url(Pictures/Slippper.jpg), auto;
}

@media (max-width: 425px) {
}

@media (max-width: 768px) {
}

@media (max-width: 1024px) {
}

@media (max-width: 1440px) {
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="style.css">
     <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> 
     <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.11.2/css/all.css" integrity="sha384-KA6wR/X5RY4zFAHpv/CnoG2UW1uogYfdnP67Uv7eULvTveboZJg0qUpmJZb5VqzN" crossorigin="anonymous">
    <title>Kill the Roach!</title>
</head>

<body class="body">

    <div class="container text-center">
        <h1>Kill the Roach!</h1>
            <p class="">Picture this, it's been a long hard week/ It's friday and all you want to do is get some rest. When suddenly you see a nasty cockroach on your wall! So you pick up a slipper and goes after him!</p>
       
        <h4>Score: <span id="score">0</span></h4>
        <h5 id="counter" class="hide">00: 00: 00</h5>
        <button id="start">Start Game</button>
        <button id="end-game">End Game(This should be some rule like 2 minute 20 roach)</button>
    </div>

    <div class="roach-box container">
        <div class="row">
            <div class="col-4 box"></div>
            <div class="col-4 box"></div>
            <div class="col-4 box"></div>
            <div class="col-4 box"></div>
            <div class="col-4 box"></div>
            <div class="col-4 box"></div>
        </div>
        <div class=" text-center">
            <h2 class="winner-text"></h2>
            <button id="play-again" class="hide">Play again!</button>
        </div>
    </div>

    <audio controls id="roach" class="hide">
        <source  src="Sounds/roach.mp3" >
    </audio>
    <audio controls id="slap" class="hide">
        <source  src="Sounds/slap.mp3" >
    </audio>
   
    

    

    <script src="script.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js?fbclid=IwAR1werSn4O58WhS56QN4-EFnLh4T6wrnQdCkwBsQAT_1aQhrys5NHPEqjgU"></script>
</body>
</html>
0 голосов
/ 08 марта 2020

Я нашел ответ! Все, что мне нужно было сделать, это создать пустое значение let вне области действия функций, а затем назначить let для setinterval внутри функции. Это позволило мне очистить его позже, когда было выполнено условие! Ниже приведен фрагмент кода, который показывает, как это работает. Я люблю javascript!

let selectBoxFunction;

function startGame() {
    selectBoxFunction = setInterval(selectBox, 1000);

}


function checkScore() {
    let scoreInnerText = score.innerText;
    if (counter.innerHTML === '00: 10: 01' && +scoreInnerText >= 5) {
        winnerText.innerHTML =
            'Wohooo! You are the king of roach killing! You are now safe from any further cockroach attacks';
        playAgainBtn.classList.remove('hide');
        clearInterval(timer);
        clearInterval(selectBoxFunction);
    } else if (counter.innerHTML === '00: 10: 01' && +scoreInnerText < 5) {
        winnerText.innerHTML =
            'Uh-oh, you failed to kill the cockroach and he and his family will be your room mates forever (and ever!)';
        playAgainBtn.classList.remove('hide');
        clearInterval(timer);
        clearInterval(selectBoxFunction);
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...