简体   繁体   中英

Push function is not working properly localStorage Javascript vanilla

I am doing a time-to-click game as you can imagine the fastest time would be the first place. I just want to have 3 scores. and have it on localstorage but every time I start a new game the actual score resets its value and it doesnt generate other scores. the 3 scores should have as value 0. I tried to push them as arrays but push function is not working well. at this point I am stuck. I dont know what to do. If u may help me, I would be really grateful, thanks!

let times = Array.from({
  length: 3
})


let interval2;

// Timer CountUp
const timerCountUp = () => {
  let times = 0;
  let current = times;

  interval2 = setInterval(() => {
    times = current++
    saveTimes(times)
    return times
  }, 1000);
}

// Saves the times to localStorage
const saveTimes = (times) => {
  localStorage.setItem('times', JSON.stringify(times))
}


// Read existing notes from localStorage
const getSavedNotes = () => {
  const timesJSON = localStorage.getItem('times')

  try {
    return timesJSON ? JSON.parse(timesJSON) : []
  } catch (e) {
    return []
  }
}

//Button which starts the countUp
start.addEventListener('click', () => {
  timerCountUp();
})

// Button which stops the countUp
document.querySelector('#start_button').addEventListener('click', (e) => {
  console.log('click');
  times.push(score = interval2)
  getSavedTimes()

  if (interval) {
    clearInterval(interval);
    clearInterval(interval2);
  }
})

This:

// Button which stops the countUp
document.querySelector('#start_button').addEventListener('click', (e) => {

Probably should be this:

// Button which stops the countUp
document.querySelector('#stop_button').addEventListener('click', (e) => {

...considering you're already attaching an event-handler to start 's 'click' event in the previous statement, and no-one would use #start_button as the id="" of a stop button.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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