Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create Semaphore between HTML elements loaded async

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.

like image 818
Himberjack Avatar asked Nov 16 '10 12:11

Himberjack


1 Answers

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:

if (!window.myUniqueNameFlag) {
    window.myUniqueNameFlag = true;
    // Do your processing
}

But again, putting things on window is not ideal if you can avoid it, although it's very common practice. (Any variable you declare at global scope with var¹ is a property of window, 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:

function foo() {
    // ...your processing...
}

Do this:

var foo = (function() {
    var flag = false;

    function foo() {
        if (!flag) {
            flag = true;
            // ...your processing...
        }
    }

    return foo;
})();

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 foo variable. You can call foo and you'll get the nested function. The nested function has an enduring reference to the flag variable 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:

function foo() {
    if (!foo.flag) {
        foo.flag = true;
        // ...do your processing...
    }
 }

Functions are just objects with the ability to be called, so you can add properties to them.


¹ Variables declared at global scope with let or const are globals, but do not become properties of window.

like image 68
T.J. Crowder Avatar answered Oct 13 '22 16:10

T.J. Crowder