How to create Semaphore between HTML elements loaded async

喜欢而已 提交于 2019-12-03 07:38:11

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!