How to create incremental counter across multiple browser windows?

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.

enter image description here