javascript – How to create Semaphore between HTML elements loaded async

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;
        // 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.

Facebook Comments


(Visited 3 times, 1 visits today)