skip to Main Content

I want to know how to clear the interval and the score, because it works, but when it reaches over 1000 and I hit reset it doesn’t reset fully.

I tried putting the clearTimeout functions before everything else, and I tried to make it all one function, but I couldn’t figure it out. If there is an easier way to fuse them, that would be good, or any other way to do this.

const btnElement = document.getElementById("btn");
const btnElement1 = document.getElementById("btn1");
const btnElement2 = document.getElementById("btn2");
const btnElement3 = document.getElementById("btn3");
const btnElement4 = document.getElementById("btn4");
const btnElement5 = document.getElementById("btn5");
const spnElement = document.getElementById("span");
let score = 1;

let intervalTimer;
let intervalTimer1;
let intervalTimer2;
let intervalTimer3

btnElement2.addEventListener("click", () => {
  if (score < 10) {
    console.log("poor");
  } else if (score >= 10) {
    score -= 10;
    spnElement.innerText = score;
    intervalTimer = setInterval(increment, 1000);

    function increment() {
      score = score % 1000000 + 1;
      spnElement.innerText = score;
    }
  }
})

btnElement3.addEventListener("click", () => {
  if (score < 30) {
    console.log("poor");
  } else if (score >= 30) {
    score -= 30;
    spnElement.innerText = score;
    intervalTimer1 = setInterval(increment1, 1000);

    function increment1() {
      score = score % 1000000 + 5;
      spnElement.innerText = score;
    }
  }
})

btnElement4.addEventListener("click", () => {
  if (score < 80) {
    console.log("poor");
  } else if (score >= 80) {
    score -= 80;
    spnElement.innerText = score;
    intervalTimer2 = setInterval(increment2, 1000);

    function increment2() {
      score = score % 1000000 + 10;
      spnElement.innerText = score;
    }
  }
})

btnElement5.addEventListener("click", () => {
  if (score < 200) {
    console.log("poor");
  } else if (score >= 200) {
    score -= 200;
    spnElement.innerText = score;
    intervalTimer3 = setInterval(increment3, 1000);

    function increment2() {
      score = score % 1000000 + 30;
      spnElement.innerText = score;
    }
  }
})

btnElement.addEventListener("click", () => {
  spnElement.innerText = score++;
})

btnElement1.addEventListener("click", () => {
  clearTimeout(intervalTimer);
  clearTimeout(intervalTimer1);
  clearTimeout(intervalTimer2);
  clearTimeout(intervalTimer3);
  spnElement.innerText = 0;
  score = 1;
})

document.body.addEventListener("keyup", function(event) {
  if (event.code === "Space") {
    spnElement.innerText = score++;
  }
})

document.body.addEventListener("keydown", function(event) {
  if (event.code === "Space") {
    spnElement.innerText = score;
  }
})

document.body.addEventListener("keydown", function(event) {
  if (event.code === "Enter") {
    clearTimeout(intervalTimer);
    clearTimeout(intervalTimer1);
    clearTimeout(intervalTimer2);
    clearTimeout(intervalTimer3);
    spnElement.innerText = 0;
    score = 1;
  }
})
body {
  background-color: moccasin;
  color: #333;
  font-family: Arial, Helvetica, sans-serif;
}

#header {
  background-color: whitesmoke;
  position: absolute;
  right: 0;
  top: 0px;
  margin: 0px;
  border-width: 2px;
  border-bottom-width: 2px;
  border-bottom-color: #333;
  border-bottom-style: solid;
  width: 100.09%;
}

#btns {
  text-align: center;
  font-family: Arial, Helvetica, sans-serif;
  margin: 135px;
}

.btns {
  background-color: dimgray;
  color: whitesmoke;
  border: 0;
  border-radius: 5px;
}

.btns:hover {
  background-color: mediumpurple;
}

#upgradeButtons {
  margin: 20px;
}

#text {
  text-align: center;
}
<div id="header">
  <div id="text">
    <h1>Skibidi Clicker</h1>
    <h2><span id="span">0</span></h2>
  </div>
</div>

<div id="btns">
  <button id="btn" class="btns">+</button>
  <button id="btn1" class="btns">Reset</button><br>
  <div id="upgradeButtons">
    <button id="btn2" class="btns">Skibidi (10 clicks)</button><br>
    <button id="btn3" class="btns">Cameraman (30 clicks)</button><br>
    <button id="btn4" class="btns">Speakerman (80 clicks)</button><br>
    <button id="btn5" class="btns">Astro Toilet (200 clicks)</button>
  </div>
</div>

3

Answers


  1. The way to clear setInterval is with clearInterval (not clearTimeout as you’re using here) – see the docs: https://developer.mozilla.org/en-US/docs/Web/API/setInterval

    Login or Signup to reply.
  2. For any given button, you’re storing a single value for the interval:

    let intervalTimer;
    

    When you click the button, you write that value:

    intervalTimer = setInterval(increment, 1000);
    

    What happens when you click that button a second time? Or a third? And so on? You overwrite the previous value.

    When resetting the game, you clear the interval:

    clearTimeout(intervalTimer);
    

    (Which, incidentally, should be using clearInterval() instead. The two are technically interchangeable, but should be kept separate for clarity.)

    This only clears the most recent interval that you stored. All of the previous ones are still running because you never cleared those, and can’t clear them because you don’t have their ID values anymore.

    If you need to store multiple values, use an array:

    let intervalTimers = [];
    

    Push each new value onto the array:

    intervalTimers.push(setInterval(increment, 1000));
    

    And clear all of the intervals stored in the array:

    intervalTimers.forEach(clearInterval);
    
    Login or Signup to reply.
  3. The main error in the code is that in the event of pressing the button, it is not checked whether the timer is already running or not, which generates the creation of a new timer, and the link (timer ID) to the previous timer is overwritten.
    Therefore, when "stopping", all saved timers are reset (no more than 4), and the rest continue to work.

    The lack of checking for a working timer will be considered an idea, not a mistake.

    Below is the code, with the duplicate code removed, how you can implement your task with starting many timers and stopping all in one click.

    const btnElement = document.getElementById("btn");
    const btnElement1 = document.getElementById("btn1");
    const spnElement = document.getElementById("span");
    let score = 0;
    
    const buttonContainer = document.getElementById('upgradeButtons');
    // array of buttons for create
    const buttons = [
        { name: 'Skibidi', scoreNeed: 10, scoreInc: 1},
        { name: 'Cameraman', scoreNeed: 30, scoreInc: 5},
        { name: 'Speakerman', scoreNeed: 80, scoreInc: 10},
        { name: 'Astro Toilet', scoreNeed: 200, scoreInc: 30},
    ];
    // all created intervals
    const intervals = [];
    // do create action buttons from array
    buttons.forEach(button => {
      const addButton = document.createElement('button'); // create btn
      addButton.classList.add('btns'); // add class
      addButton.innerText = `${button.name} (${button.scoreNeed} clicks)`; // add text
      addButton.addEventListener('click', () => { // add listener
        if (score < button.scoreNeed) {
          console.log('poor');
        } else {
          score -= button.scoreNeed;
          spnElement.innerText = score;
          let timerId = setInterval(() => {
            score = score % 1000000 + button.scoreInc;
            spnElement.innerText = score;
          }, 1000);
          intervals.push(timerId);
        }
      })
      buttonContainer.appendChild(addButton); // append in DOM
    })
    
    function inc() {
      spnElement.innerText = score++;
    }
    
    function clear() {
      intervals.forEach(clearInterval); // stop all intervals
      intervals.length = 0; // clear array
      spnElement.innerText = 0;
      score = 1;
    }
    
    btnElement.addEventListener("click", inc);
    btnElement1.addEventListener("click", clear);
    document.body.addEventListener("keyup", function(event) {
      if (event.code === "Space") inc();
    });
    
    document.body.addEventListener("keydown", function(event) {
      if (event.code === "Enter") clear();
    });
    body {
      background-color: moccasin;
      color: #333;
      font-family: Arial, Helvetica, sans-serif;
    }
    
    #header {
      background-color: whitesmoke;
      position: absolute;
      right: 0;
      top: 0px;
      margin: 0px;
      border-width: 2px;
      border-bottom-width: 2px;
      border-bottom-color: #333;
      border-bottom-style: solid;
      width: 100.09%;
    }
    
    #btns {
      text-align: center;
      font-family: Arial, Helvetica, sans-serif;
      margin: 135px;
    }
    
    .btns {
      background-color: dimgray;
      color: whitesmoke;
      border: 0;
      border-radius: 5px;
    }
    
    .btns:hover {
      background-color: mediumpurple;
    }
    
    #upgradeButtons {
      margin: 20px;
      display: flex;
      flex-direction: column;
      align-items: center;
    }
    
    #upgradeButtons>.btns {
      background-color: dimgray;
      color: whitesmoke;
      border: 0;
      border-radius: 5px;
      margin: 3px;
      width: 175px;
      justify-content: center;
    }
    
    #text {
      text-align: center;
    }
    <div id="header">
      <div id="text">
        <h1>Skibidi Clicker</h1>
        <h2><span id="span">0</span></h2>
      </div>
    </div>
    
    <div id="btns">
      <button id="btn" class="btns">+</button>
      <button id="btn1" class="btns">Reset</button><br>
      <div id="upgradeButtons">
      </div>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search