I've tried to use localStorage to sync a counter across multiple windows and I've found that since localStorage doesn't have a lock it is possible to have racing issue.
const root = document.getElementById('root');
let thisCounter = 0;
const interval = setInterval(() => {
const counter = parseInt(localStorage.getItem('counter') || 0, 10);
localStorage.setItem('counter', `${counter + 1}`);
++thisCounter;
root.innerHTML = `global: ${counter + 1}, this: ${thisCounter}`;
if (thisCounter >= 500) {
clearInterval(interval);
}
}, 100);
And when I open three Chrome browser windows (having separated threads) it appears that the counter would eventually run to 1498 or 1497 instead of 1500.
Separate the read and write operations.
You can use a JSON array structure to designate individual variables for each browser window for write operations. When you need to read, you can access all the individual variables and add them together.