Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”

This article has participated in the “Digitalstar Project” and won a creative gift package to challenge the creative incentive money.

The difference between jquery, Axios and FETCH

Jquery Ajax: A wrapper around native XHR with additional JSONP support. But a large JQ library needs to be introduced for this functionality, and asynchronous support is not very friendly

Axios Ajax: An HTTP client based on Promise for browsers and NodeJS, which is essentially a wrapper around native XHR, but it’s a Promise implementation that complies with the latest ES specification and is the mainstream Ajax library in use today

Fetch: Uses the Promisse object in ES6. However, fetch is not a further encapsulation of Ajax, but rather native JS, without using the XMLHttpRequest object.

To sum up: jquery Ajax is a no-no. For serious project development, I suggest using Axios. If it’s not serious, or if it’s a small demo, just use the native fetch

Scenario assumptions

We need to poll an interface and do some processing on the returned data, and we can use setInterval

The approximate code would look like this:

let timeId = setInterval(() = > {
    fetch(url, config)
}, time)
Copy the code

There is a problem with this approach. The operation in fetch is asynchronous. It is assumed that it takes 2s to get the result after the execution, but the polling interval is 1s

When we talk about setInterval, we have to mention macro tasks, which are the main tasks that the browser is currently performing, and micro tasks, which are side tasks, which are two ordered queues. When the main task is completed at the current time point, a secondary task will be used as the main task, and the loop will continue until both tasks are completed.

SetInterval, on the other hand, is responsible for generating tasks at a certain time, and then throwing them to a branch queue, which just generates them and doesn’t execute them. As for when to do it, you need the browser’s thread to schedule it. The scheduling is based on the previous paragraph

In summary, setInterval, the time parameter passed in, is not the interval between the execution of multiple tasks, but the interval between the next task. When to execute this task depends on the current operating environment of the system

To improve the

Wrap a function named call for fetch. In the fetch execution result, use setTimeout to execute the next call. The whole call chain is similar to a linked list, and the next call will be executed only after the current function is completed

{
    call();
    function call(time = 1200) {
        fetch("https://cn.bing.com/hp/api/model", {
            "headers": {
                "accept": "* / *"."accept-language": "zh-CN,zh; Q = 0.9"."content-type": "application/json"."sec-ch-ua": "\"Chromium\"; v=\"94\", \"Google Chrome\"; v=\"94\", \"; Not A Brand\"; v=\"99\"",},"referrer": "https://cn.bing.com/"."referrerPolicy": "strict-origin-when-cross-origin",
        }).then(rep= > rep.json()).then((data) = > {
            setTimeout(() = >call(time), time) }); }}Copy the code

What if it’s conditional termination?

Further thinking, take the lottery interface of the nuggets as an example, we have 1000 mines in hand, but the actual number of lottery, not necessarily 5 times, the termination condition becomes: continue to draw until the lottery interface returns the lottery failure

The idea is: we introduce a flag, define flag= true to draw, flag=false to end the draw

  1. incallThe first line in the
    1. flagforfalseTerminates, and executes the statistics function to output everyone’s results
    2. If it istrueThe callfetch
  2. infetchUsed in the callbacksetTimeoutTo define the next call
  3. According to the results of this time to determine whether adjustment is neededflagfalse

The general code is as follows:

function choujiang() {
    let nextLotteryFlag = true;
    asyncFetch(() = > {})

    function asyncFetch(callback, time = 1200) {
        if(! nextLotteryFlag) { callback();return;
        };
        setTimeout(() = > {
            fetch(`https://api.juejin.cn/growth_api/v1/lottery/draw?${userInfo}`, httpConfig)
                .then(resp= > resp.json()).then(data= > {
                    if (data.err_msg == 'success') {
                        console.log(name);
                    } else {
                        nextLotteryFlag = false;
                    }
                    asyncFetch(callback, time);
                })
        }, time)
    }
    return false;
}

Copy the code

Original is not easy, look forward to everyone’s encouragement ❤~