简体   繁体   English

在递归JQuery / Javascript自执行函数中设置变量(轮询)

[英]Setting a variable in a recursive JQuery/Javascript self-executing function (polling)

I need to set a variable ( tick) with an initial value in a recursive self-executing JQuery script. 我需要在递归自执行JQuery脚本中设置一个具有初始值的变量( 刻度) When I try and run the script below obviously tick is going to revert back to 0 rather than the value the JSON object is returned with. 当我尝试运行以下脚本时,很显然滴答号将还原为0,而不是返回JSON对象的值。

    (function poll(){
        var tick = 0;
        setTimeout(function(){
            $.ajax({
                url: "/client-polling/" + tick,
                success: function(data) {
                    $( "#messagestack" ).append(data[2]);
                    tick = data[0]
                },
                dataType: "json",
                complete: poll
            });
        }, 10000);
    })();

Also for some reason when I have tick declared the function waits the entire 10 seconds before polling the first time. 同样由于某种原因,当我声明了滴答声时,该函数将等待整个10秒,然后才进行第一次轮询。 If I try to declare tick outside of the function all other scripts on the page freeze up. 如果我尝试在函数外部声明tick ,则会冻结页面上的所有其他脚本。

Where do I declare tick so the first time the page is called it's set to 0 and then takes the value from the returned JSON object? 我在哪里声明滴答声,以便第一次调用该页面时将其设置为0,然后从返回的JSON对象中获取值?

Update: Well it took most of the Eloquent Javascript book and 7 Douglas Crockford videos to figure out what the problem was and I had failed to realise that Javascript is single-threaded. 更新:嗯,花了大部分Eloquent Javascript书籍和7道格拉斯·克罗克福德(Douglas Crockford)的视频来弄清楚问题出在哪里,而我却没有意识到Javascript是单线程的。 I've read through so much of other peoples coding it had not really occurred to me that usually their scripts run through once and go on to the next. 我已经阅读了很多其他人的编码,但实际上我的脚本没有运行过,通常他们的脚本运行一次,然后继续运行下一个。 My 'event-loop' was stopping other scripts from running, and yes, on its own the function should have the variable on the outside. 我的“事件循环”正在阻止其他脚本运行,是的,该函数本身应该在外部具有变量。

I finally ended up using iFrames (non-public, single interface application so security not a concern) just to get it running and now looking at web workers for future builds. 最后,我最终使用了iFrames(非公共,单接口应用程序,因此安全性不是问题),只是为了使其运行,现在是在为将来的构建寻找Web工作者。 Thanks for the answers so far. 到目前为止,感谢您的回答。

Why don't just set a variable outside the function? 为什么不只是在函数外部设置变量?

var tick = 0;
(function poll(){
    setTimeout(function(){
        $.ajax({
            url: "/client-polling/" + tick,
            success: function(data) {
                $( "#messagestack" ).append(data[2]);
                tick = data[0]
            },
            dataType: "json",
            complete: poll
        });
    }, 10000);
})();

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

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