Proxy mode of JavaScript design pattern-performance optimization of frequent requests

Before reading this article, it is recommended to look at the proxy mode of the previous JavaScript design pattern-realize loading image loading

1. Demand

Suppose we are doing a file synchronization function, when we select a checkbox, its corresponding file will be synchronized to another backup server.

2. Realize

First, we create n checkboxes in html:

<body>
    <input type="checkbox" id="1" />1
    <input type="checkbox" id="2" />2
    <input type="checkbox" id="3" />3
    <input type="checkbox" id="4" />4
    <input type="checkbox" id="5" />5
    <input type="checkbox" id="6" />6
    <input type="checkbox" id="7" />7
    <input type="checkbox" id="8" />8
    <input type="checkbox" id="9" />9
</body>
  • Send http request without virtual proxy
const syncFile = function (id) {
    console.log(`开始同步文件,id为:${id}`);
}
const checkbox = document.getElementsByTagName('input');
checkbox.map(c => {
    c.onclick = function () {
        if (this.checked === true) {
            syncFile(this.id);
        }
    }
})

If implemented in this way, when the user clicks on the checkbox in rapid succession for a period of time, it will cause multiple requests to be sent at the same time. Such frequent network requests will bring considerable overhead.

  • Use virtual proxy to merge http requests
const syncFile = function (id) {
    console.log(`开始同步文件,id为:${id}`);
}
const proxySyncFile = function () {
    let cache = [], // 保存一段时间内需要同步的ID
        timer;      // 定时器
    return function (id) {
        cache.push(id);
        if (timer) { // 保证不会覆盖已经启动的定时器
            return;
        }
        timer = setTimeout(function(){
            syncFile(cache.join(',')); // 2秒后向本体发送需要同步的ID集合
            clearTimeout(timer);       // 清空定时器
            timer = null;
            cache.length = 0;          // 清空ID集合
        }, 2000);
    }
}
const checkbox = document.getElementsByTagName('input');
checkbox.map(c => {
    c.onclick = function () {
        if (this.checked === true) {
            proxySyncFile(this.id);
        }
    }
})

To solve frequent requests, we use a proxy function proxySyncFile to collect requests within a period of time, and finally send them to the server at one time.

3. Summary of ideas

When we encounter frequent network requests for the same period of time, we can create a virtual proxy object, cache the requests for this period of time, use the timer, and then issue the merged request before n seconds. So multiple requests become one request, greatly optimizing performance.

Note: Reference book "JavaScript Design Patterns and Development Practice"

Guess you like

Origin blog.csdn.net/qq_39287602/article/details/108749706