0

I am just starting with javascript. I want to modify a simple counter code to let it accept parameter when the count() function is called. But it just does not work. Please help. Thanks.

const clickEl = document.querySelector("#click");
const resetEl = document.querySelector("#reset");
const h1El = document.querySelector("h1");

var counts = 0;
if (localStorage.getItem("counts") !== NaN) {
    counts = localStorage.getItem("counts");
    h1El.innerHTML = `${counts}`;
} 

clickEl.addEventListener("click", count(1));
resetEl.addEventListener("click", () => {
    counts = 0;
    localStorage.setItem("counts", counts);
    h1El.innerHTML = `${counts}`;
});
setInterval(count(3), 1000);

function count(n) {
    counts += n;
    localStorage.setItem("counts", counts);
    h1El.innerHTML = `${counts}`;
}
  • the event handlers need to be functions, not the result of calling functions - example, `count(1)` calls the function ... `() => count(1)` IS a function – Jaromanda X Aug 18 '22 at 08:37
  • Thanks. I updated the code to the following and they work now. clickEl.addEventListener("click", () => count(1)); setInterval(() => count(3), 1000); – Victor Zhang Aug 18 '22 at 09:03
  • well, there is a better way ... the correct way ... setInterval expects a function as an argument, and you're providing the result of calling the function ... same deal as with the event handler – Jaromanda X Aug 18 '22 at 09:03
  • Just found out there is an even simpler way. setInterval(count, 1000, 3); – Victor Zhang Aug 18 '22 at 09:08
  • yes, there is that - not many people know that – Jaromanda X Aug 18 '22 at 09:32

0 Answers0