How to create a semaphore between HTML elements loaded by async

I have on an HTML page an element that appears several times and works with the same JS. The problem is that I want her to perform a certain function only if she was the first to launch it (his brothers and sisters never started it - YET).

I need a semaphore to synchronize between them. I cannot know how to declare a variable and make a semaphore this way in JS.

+6
javascript html semaphore
Nov 16 '10 at 12:57
source share
1 answer

There are many approaches.

You need to put a flag somewhere. In the absence of anything else, you can put it on a window , but use a name that is unlikely to conflict with anything else.

Then JavaScript is pretty simple:

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

But then again, putting things on a window not ideal if you can avoid it, although this is a very common practice. (Any function or variable declared in the global scope is a window property.)

If your function is already declared in the global scope (and therefore already occupies a character), you can do this to avoid creating a second character. Instead:

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

Do it:

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

It looks complicated, but it is not: we define an anonymous function in which we define a variable and a nested function, then return a reference to the nested function and assign it to the external variable foo . You can call foo and you will get a nested function. The nested function has a permanent reference to the flag variable, because it closes the variable , but no one sees it. It is completely closed.

A third option is to simply use the flag for 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.

+7
Nov 16 '10 at 12:59
source share



All Articles