代理模式——虚拟代理合并HTTP请求

69 阅读1分钟
有以下一个场景:

每选中一个文件,便向服务器发送一次同步文件的请求。而用户如果在一秒钟点击了4个文件,可以预见频繁的网路请求会带来相当大的开销。

解决方案:

通过一个代理函数来收集一段时间内的请求,最后一次性发给服务器。

代码如下:
<body>
    <input type="checkbox" id="1"></input>1
    <input type="checkbox" id="2"></input>2
    <input type="checkbox" id="3"></input>3
    <input type="checkbox" id="4"></input>4
    <input type="checkbox" id="5"></input>5
    <input type="checkbox" id="6"></input>6
    <input type="checkbox" id="7"></input>7
    <input type="checkbox" id="8"></input>8
    <input type="checkbox" id="9"></input>9
   <script>
       var synchronousFile = function( id ){
           console.log('开始同步文件, id为:' + id)
        };
        var proxySynchronousFile = (function() {
            let timer = null
            let cache = []
            return function(id) {
                cache.push(id)
                if (timer) {
                    return false
                }
                timer = setTimeout(() => {
                    synchronousFile(cache.join(','))
                    clearTimeout(timer)
                    timer = null
                    // cache = []
                    cache.length = 0
                }, 2000)
            }            
        })()
     var checkbox = document.getElementsByTagName( 'input' );
     for(var i = 0, c; c = checkbox[i++];) {
         c.onclick = function() {
             if (this.checked === true) {
                 proxySynchronousFile( this.id );
             }
         }
     }

   </script>
</body>