如何在 JavaScript 中实现锁 [英] How to implement a lock in JavaScript
问题描述
如何在 JavaScript 中实现与 C# 中的 lock
等效的东西?
How could something equivalent to lock
in C# be implemented in JavaScript?
所以,为了解释我的想法,一个简单的用例是:
So, to explain what I'm thinking a simple use case is:
用户点击按钮B
.B
引发一个 onclick 事件.如果B
处于event-state
,则事件在传播之前等待B
处于ready-state
.如果B
处于ready-state
,B
被锁定并设置为event-state
,则事件传播.当事件传播完成后,B
设置为 ready-state
.
User clicks button B
. B
raises an onclick event. If B
is in event-state
the event waits for B
to be in ready-state
before propagating. If B
is in ready-state
, B
is locked and is set to event-state
, then the event propagates. When the event's propagation is complete, B
is set to ready-state
.
我可以看到如何完成与此类似的事情,只需从按钮中添加和删除 ready-state
类即可.但是,问题在于用户可以比设置变量更快地连续单击按钮两次,因此在某些情况下,这种锁定尝试会失败.
I could see how something close to this could be done, simply by adding and removing the class ready-state
from the button. However, the problem is that a user can click a button twice in a row faster than the variable can be set, so this attempt at a lock will fail in some circumstances.
有谁知道如何在 JavaScript 中实现一个不会失败的锁?
Does anyone know how to implement a lock that will not fail in JavaScript?
推荐答案
Lock 在 JS 中是一个有问题的想法,它旨在实现无线程并且不需要并发保护.您希望结合对延迟执行的调用.我遵循的模式是使用回调.像这样:
Lock is a questionable idea in JS which is intended to be threadless and not needing concurrency protection. You're looking to combine calls on deferred execution. The pattern I follow for this is the use of callbacks. Something like this:
var functionLock = false;
var functionCallbacks = [];
var lockingFunction = function (callback) {
if (functionLock) {
functionCallbacks.push(callback);
} else {
$.longRunning(function(response) {
while(functionCallbacks.length){
var thisCallback = functionCallbacks.pop();
thisCallback(response);
}
});
}
}
您也可以使用 DOM 事件侦听器或发布订阅解决方案来实现这一点.
You can also implement this using DOM event listeners or a pubsub solution.
这篇关于如何在 JavaScript 中实现锁的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!