Reputation: 27
I am building a incremental game. I have a progress bar that fills up 1 point every second.. And when that bar reaches 10 points it resets back to 0..
The problem I am having is checking if the variable is 10 at all times. I am currently using setInterval to run the function every 10 milliseconds but I feel like this is not good for the website.
I have been trying to find a solution for this for months, can someone please help me out here..
In short: How do I check a variables value at all times without causing lag/inefficiency
Upvotes: 0
Views: 75
Reputation: 206078
So, to recap, you're running a setInterval
at 10ms which task is just to check if the value of some variable equals 10
. There's so many solutions, but hard to answer specifically without seeing any code.
Solution 1: Call a desired function immediately after where you increment your variable
const doTheMagic = (points) => {
console.log(`You reached score: ${points}`)
};
let points = 0; // Start at 0
const incrementPoint = () => {
points += 1;
if (points === 10) doTheMagic(points);
points %= 10; // Loop-back points to 0 when reaches 10
};
// You say you increment `points` at intervals of ~1000ms:
setInterval(incrementPoint, 1000);
Wait 10s... Then again 10s... etc...
Solution 2: Use setter
Solution 3: Use Proxy
Upvotes: 2