开发者

Convert a javascript timer function to use asynchronous calls

开发者 https://www.devze.com 2023-02-14 22:13 出处:网络
I have this javascript function, which uses a timer to call an ajax file every 2 seconds. However, I see that this data is sent to the ajax file before the execution of previous data is complete. That

I have this javascript function, which uses a timer to call an ajax file every 2 seconds.

However, I see that this data is sent to the ajax file before the execution of previous data is complete. That is, it sends the whole list in about 10 seconds, while the data takes around 120 seconds to be processed.

Is there a way, I can send the next data node, only when the previous has finished processing? cb.call(this) is being used to call a function, when this timer is finished,

while querylimit is a response variable, which exits the function if its true.

var i = 0;
var querylimit=false;
function refr开发者_开发知识库eshTimer(list,cb,i){
    if (!(i >= 0)) { i= 0; }
    setTimeout((function(chunk){
        i++;
        return function(){
            if (querylimit) { cb.call(this); }
            if(i <= list.length && !querylimit){
                refreshTimer(list,cb,i);
                refreshClients(chunk);
            }
            if(i == list.length+1) { cb.call(this); }
            if(i > list.length+1 || querylimit) { return null; }
        }
    }) (list[i]), 2000);
}

Regards

Nikhil Gupta


I typically setup what I call a "cascade", which is a chain reaction of window.setTimeout(...) calls, rather than a single window.setInterval(...) call.

Instead of:

function requestAjaxData() {
    // prep ajax / call onAjaxDataReceived on success.
}
function onAjaxDataReceived() {
    // process data
}
window.setInterval(requestAjaxData, 2000);

I do:

function requestAjaxData() {
    // prep ajax / call onAjaxDataReceived on success.
}
function onAjaxDataReceived() {
    // process data

    // continue the cascade
    requestAjaxDataCascade();
}
function requestAjaxDataCascade() {
    window.setTimeout(requestAjaxData, 2000);
}
requestAjaxDataCascade();
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号