如何在JavaScript中实现锁 [英] How to implement a lock in JavaScript

查看:298
本文介绍了如何在JavaScript中实现锁的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在C#中实现与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 事件状态中,事件将等待 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?

推荐答案

在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事件侦听器或pubsub解决方案。

You can also implement this using DOM event listeners or a pubsub solution.

这篇关于如何在JavaScript中实现锁的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆