简体   繁体   English

jQuery / AJAX并发访问全局变量

[英]jQuery/AJAX concurrent access to global variable

I'm writing some jQuery code that performs a plain ajax call. 我正在编写一些执行简单的ajax调用的jQuery代码。 I've a global Javascript variable that I need to increase thread-safely with every call. 我有一个全局Javascript变量,我需要在每次调用时增加线程安全性 If this was Java, I would use synchronized but this is not the case :-) 如果这是Java,我会使用synchronized但事实并非如此:-)

Here's a code snippet: 这是一段代码片段:

var myval;

function myFunc()
{
    $.ajax({
        url: myurl,
        type: 'GET',
        data: { ...my data... },
        success: function()
        {
            myval++;
        }
    });
}

Given that myFunc() is associated with a click event, how can I be sure that myvar is always safely/consistently increased? 鉴于myFunc()与click事件相关联,我如何确保myvar始终安全/持续增加? I know I could maybe use async: false , but I'd prefer to avoid it. 我知道我可能使用async: false ,但我宁愿避免它。 I'm not even sure it would work that way. 我甚至不确定它会那样工作。

Thanks for any help! 谢谢你的帮助!

There's no problem - JS doesn't suffer atomicity problems since there are no (user-visible) threads[*] 没有问题 - JS没有原子性问题,因为没有(用户可见的)线程[*]

Nothing happens in JS except in response to an event or initial script load. 除了响应事件或初始脚本加载之外,JS中没有任何事情发生。 It's impossible for a piece of code to misread myval during an increment, because the entire success callback must complete before any other event handling code can start. 在增量期间,一段代码不可能误读myval ,因为整个success回调必须在任何其他事件处理代码开始之前完成。

[*] Yes, there's WebWorkers, but they use message passing not variable sharing. [*]是的,有WebWorkers,但他们使用消息传递而不是变量共享。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM