Doua Beri Doua Beri - 3 months ago 18
Javascript Question

javascript synchronize code execution between tabs

I have a dilemma. I'm using this code to generate an unique ID and store it in a cookie or local storage. I'm only generating this ID if there is no previous ID set.

//read the ID from cookie or local storage
var id=readID();
//no ID found, generate an ID

//store the ID to use it when we come back

This code works as I expected around 90% of the time, generating only one ID, but sometimes when a user with no ID opens 2 or more tabs in the same time(or on very short intervals) it ends up generating 2 IDs.
What I'm interested is some hack strategy to lock the code when reading,generating and storing the ID, and to be executed only in one tab. until the lock is released.

I know this might not work because tabs are separated, but I was thinking if you could lock on a local storage object for both read and write?

I'm open to other solutions as well.

UPDATE: I was asked how generateID algorithm is. I say it doesn't matter, but to simplify this we'll use
like this:

function generateID(){
return Math.random();


Assuming your readID function is quick. Try this:

const now = new Date().getTime() // Number -> 1471016775000 (ms since epoch)
const id = readID()
if (!id) {
    id = generateID()
    const lookup = readID()
    if (lookup === now) {
        // this confirms this is the window that started generating the ID