简体   繁体   中英

Hold ajax call in every minute calling section

i am calling ajax every second in page.. Here the server page returns randomly generated number ,using this number( converted into seconds ) i am triggering another function in ajax success .it works

My problem

suppose random number = 5 means trigger() function called after 5 seconds using setTimeout ,but rember ajax call is triggering every 1 second so trigger function also called many time.

i want to make ajax call wait untill trigger function execution .Which means i wanna pause that ajax call untill 5 seconds after that resume

How can i do this ?

My coding

//this ajax is called every minute
        $.ajax({
            type: "POST",
            url: 'serverpage', 
            data: ({pid:1}),
            success: function(msg) { 

                var array = msg.split('/');
                if(array[0]==1){
                setTimeout(function() {  trigger(msg);          },array[1]+'000');
             }
            }

        }); 


//and my trigger function
function trigger(value)
{
    alert("i am triggered !");
}

server response maybe

1/2 or 1/5 or 1/ 10 or 1/1

here 1/ 3(this is converted into seconds)

It looks like you should fire the ajax call in your trigger function, or on the error callback. Fire it once at page ready, and then fire it when your success function is called.

function ajaxCall() {
    $.ajax({
        type: "POST",
        url: 'serverpage', 
        data: ({pid:1}),
        success: function(msg) { 
            var array = msg.split('/');
            if(array[0]==1){
                setTimeout(function() {
                    trigger(msg);
                    ajaxCall();
                }, parseInt(array[1])*1000);
            }
        },
        error: function() {
            setTimeout(ajaxCall, 1000);
        }
    }); 
}

$(ajaxCall);

Note: you should reply with some json instead of your custom data format "1/3". Something like "{success:1,delay:3}" would be much more reliable.

您可以从“成功”回调函数递归调用ajax函数,或者在更好的情况下,可以从触发器函数调用ajax函数。

Rather than having your AJAX call in a timer, just recall it after each execution of the trigger function.

//and my trigger function
function trigger(value)
{
    alert("i am triggered !");
    MyAjaxFunction();
}

You have to call it once too at page load:

$(document).ready(function(){
    MyAjaxFunction();
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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