如何在异步加载的 HTML 元素之间创建信号量
我在 HTML 页面中有一个出现多次的元素,并且运行相同的 JS。 问题是,我希望它只有在第一个运行它时才执行特定功能(他的兄弟姐妹从未运行过它)。
我需要信号量在它们之间同步。 我无法知道如何在 JS 中声明变量并以这种方式执行信号量。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
有很多方法。
您需要在某处放置一个标志。如果没有其他任何内容,您可以将其放在
window
上,但使用不太可能与其他任何内容冲突的名称。那么 JavaScript 就非常简单了:
但是,如果可以避免的话,将东西放在
window
上并不是理想的选择,尽管这是非常常见的做法。 (您在全局范围内使用var
声明的任何变量都是window
的属性,您在全局范围内声明的任何函数也是如此。)如果您的函数已在全局范围内声明范围(因此已经占用了全局标识符/窗口属性),您可以这样做以避免创建第二个标识符。而不是:这样
做:
这看起来很复杂,但事实并非如此:它定义并立即调用一个匿名函数,在该函数中定义一个变量和一个嵌套函数,然后返回嵌套函数的引用并将其分配给
foo
变量。您可以调用foo
并且您将获得嵌套函数。嵌套函数对flag
变量有一个持久引用,因为它是一个 关闭变量,但其他人看不到它。这是完全私人的。第三个选项是仅在函数对象本身上使用标志:
函数只是具有被调用能力的对象,因此您可以向它们添加属性。
1 使用
let
或const
在全局范围内声明的变量是全局变量,但不会成为window
的属性。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:
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 withvar
¹ is a property ofwindow
, 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:
Do this:
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 callfoo
and you'll get the nested function. The nested function has an enduring reference to theflag
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:
Functions are just objects with the ability to be called, so you can add properties to them.
¹ Variables declared at global scope with
let
orconst
are globals, but do not become properties ofwindow
.