Reputation: 327
I am creating an app in which a user has to click on the red backgrounds to score points. The end goal is to create a hit the mole kinda game. I have created function for the red background to appear on a 1 second interval and the score to increment whenever i click and apply a class to wherever the red background class is. I am however having trouble with stopping the selectBox() and selectBox() from running at counter.innerHTML === '00: 10: 01'.
can anyone tell me where im wrong?
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();
}
Upvotes: 1
Views: 242
Reputation: 327
I found the answer! All i needed to do was create an empty let outside the scope of the functions and then assign the let to the setinterval inside the function. This allowed me to clearInterval it later on when a condition was met! Below is a snippet of code thats shows how it works. I love 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);
}
}
Upvotes: 0
Reputation: 650
It's Just clear of a list of intervals. You can call onEndGame() in checkScore() or by clicking on End Game button
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>
Upvotes: 1