javascript - How to create Semaphore between HTML elements loaded async -
i have in html page, element appears several times, , running same js. problem is, want specific function if first 1 run (his siblings never ran - yet).
i need semaphore sync between them. unable know how declare variable , semaphore in way in js.
there lots of approaches.
you need put flag somewhere. in absense of else, can put on window
, use name that's unlikely conflict else.
then javascript quite straightforward:
if (!window.myuniquenameflag) { window.myuniquenameflag = true; // processing }
but again, putting things on window
not ideal if can avoid it, although it's very common practice. (any function or variable declare @ global scope property of window
.)
if function declared @ global scope (and therefore occupying symbol), can avoid creating second symbol. instead of:
function foo() { // ...your processing... }
do this:
var foo = (function() { var flag = flase; function foo() { if (!flag) { flag = true; // ...your processing... } } return foo; })();
that looks complicated, it's not really: define anonymous function, within define variable , nested function, return nested function reference , assign external foo
variable. can call foo
, you'll nested function. nested function has enduring reference flag
variable because it's closure on variable, no 1 else can see it. it's private.
a third option use flag on function object itself:
function foo() { if (!foo.flag) { foo.flag = true; // ...do processing... } }
functions objects ability called, can add properties them.
Comments
Post a Comment