Front-end development: how to make a polling call to an Api interface to ensure that you can always get the return result of the last call to Api?

Front-end development: how to make a polling call to an Api interface to ensure that you can always get the result of the last call to Api?

Mar.03,2022

add a timestamp each time the API is called, and successfully call back to the resolved of / Promise to determine whether the timestamp is up-to-date.

let Api = {
    recent: 0,
    ajax(params, callback){
       // time
       let time = (this.recent = (new Date()).getTime());
       return $.get(params, complete: (data) => {
           callback(data, time);
       }); 
    },
}

// 
Api.ajax(params, (data, time) => {
    if(time === Api.time){
        // 
    }
});

Anti-shake: a function that needs to be triggered frequently, which only takes effect for the last time within a specified time, and the previous one does not.


1. Before setting a flag request to the request, determine that the flag cannot request return, and then change the flag request after the end of the request to change the flag back to the same as preventing repeated clicks.
2. The anti-shake function ensures that the function is executed once in a period of time
3. The current request library should have a manual termination method to terminate the previous request before issuing a new request


you can cache the url in the request, and then jump out of the cache. Check whether the request is in the cache first, and cancel the previous request before executing the new request.
I won't elaborate on how to cancel the request. See the link: https://blog.csdn.net/wopelo/.

Menu