Reputation: 23
TLDR:
What I was aiming for:
What is happening:
Longer:
I am currently trying to make a chrome extension that is very simple, but am stuck at a central feature. The idea is like a tamagotchi - the user clicks items, they get a heart, the heart should deplete after a while. This should continue working, even if the extension is closed and reopened. I'm therefore using chrome.local.storage to save all data.
When a heart is added, a score is saved on chrome storage, and a HTML element is added (in the "score" div). I wrote a setInterval function, that I was hoping would run every 10 seconds, evaluate hearts, and remove them if they evaluated true.
At first I thought it was removing at the speed of the function or something, but I realised (by adding many console.logs and yes, also asking chatgpt for help) that the id of the heart (when it was added) changes. This means the interval is always about 40-60 hours (even if I just "made" the element a few seconds ago), and therefore always evaluates true.
I think I am either using Date.now() wrong, or not grabbing the hearts correctly. I made the function get from storage, because that seemed most logical to me, but unsure if I should really just be grabbing the HTML elements from the page? I have really tried to exhaust my options, but being new to JavaScript, I have a nagging feeling I am simply doing something very basic wrong.
Everything else (updating when you reopen the application, playing the animations, the display showing more or less hearts) works fine.
This is how I save the time a heart was added at the moment:
heart.id = Date.now();
chrome.storage.local.set({ [heart.id]: Date.now() });
And this is the function that should check the intervals:
setInterval(function() {
// Get all the hearts in the display
const current = Date.now();
chrome.storage.local.get(null, function(result) {
for (const heartId in result) {
const interval = (current - result[heartId]);
// Check interval
if (interval > 600000) {
// Remove the heart
removeHeart(heartId);
console.log("heart removed");
break;
}
}
});
}, 10000);
This is how I remove the element from storage:
chrome.storage.local.remove(heartId);
Upvotes: 0
Views: 100
Reputation: 23
I think the issue I was using storage wrong, as it wasn't deleting the correct hearts from storage by grabbing their id (as I thought it was). I instead used an array, so I could make sure it would find the correct one, and this has solved the problem!
Implemented using the following line:
const heartsArray = result.heartsArray || [];
Upvotes: 1
Reputation: 149
Now I still don't understand why the interval can get so large, but one thing I do know is that for each heart you create a variable to store Date.now
first, like:
let date_now = Date.now();
heart.id = date_now
chrome.storage.local.set({ [heart.id]: date_now });
That way you're much less likely to encounter mutations.
Upvotes: 0