I have in an HTML page, an element that appears several times, and running the same JS.
Problem is, I want it to do a specific function only if it was the first one to run it (his siblings never ran it – YET).
I need semaphore to sync between them.
I am unable to know how to declare a variable and to do semaphore in this way in JS.
There are lots of approaches.
You need to put a flag somewhere. In the absence of anything else, you can put it on
window, but use a name that’s unlikely to conflict with anything else.Then the JavaScript is quite straightforward:
But again, putting things on
windowis not ideal if you can avoid it, although it’s very common practice. (Any variable you declare at global scope withvar¹ is a property ofwindow, as is any function you declare at global scope.)If your function is already declared at global scope (and therefore already occupying a global identifer / window property), you can do this to avoid creating a second identifer. Instead of:
Do this:
That looks complicated, but it’s not really: It defines and immediately invokes an anonymous function, within which it defines a variable and a nested function, then it returns the nested function’s reference and assigns it to the
foovariable. You can callfooand you’ll get the nested function. The nested function has an enduring reference to theflagvariable because it’s a closure over the variable, but no one else can see it. It’s completely private.A third option is to just use a flag on the function object itself:
Functions are just objects with the ability to be called, so you can add properties to them.
¹ Variables declared at global scope with
letorconstare globals, but do not become properties ofwindow.