Rxjs solution using javascript and image stabilization and the leading end of the throttle

JavaScript implementation:

Shake

N seconds function is performed only after the trigger event once a high-frequency, high frequency n seconds if the event is triggered again, the re-calculation time;
thinking: are canceled delay before calling the method each time the trigger event:

For example: function to make an automatic query
pretending following code is acquired data server (will be used below) from: // pretend it is the interface function the getData (Val) { return new new Promise ( function (Resolve, Reject) {    

        the setTimeout ( function () {
             IF ! (Val) {Resolve ([]); return ;}
             var JSON = [ 
                {name: "Xiaoshan International Airport", jianpin: "xsgjjc", threeCode: "the xjc" }, 
                {name: "Beijing Nanyuan Airport" jianpin: "bjnyjc" threeCode: "BYC" }, 
                {name: "Shanghai Hongqiao Airport," jianpin: "shhqjc" threeCode: "HCG" }, 
                {name: "Chengdu Airport" jianpin: "cdjc", threeCode: "CJC" } 
            ]; 
            var newJson = JSON.filter(function(item){
                return item.name.indexOf(val)==0||item.jianpin.indexOf(val)==0||item.threeCode.indexOf(val)==0
            });
            resolve(newJson);
        },1000)
    })
}

 

Keyword entered in the text box corresponding to the request to the server real-time data, the following code; <body>
    <input type="text" placeholder="简拼/汉字/三字码" id="test"/>
    <script>
        var $test = document.getElementById('test');
        $test.onkeyup =autoSearch;
        function autoSearch(){
            var val = $test.value;
            getData(val).then(function(res){console.log(res)})
        }   
    </script>
</body>

 

The results shown below, at run time will find that there is a problem: the default frequency of execution of this function is too high , to what extent high it? We enter "Xiaoshan" function performs nine times! However we need is the last time.

However, in practice we do not need such a high frequency feedback, after all, the browser and the server's performance is limited, so then discuss how to optimize this scenario.

function Debounce (Fn, Delay) { 
    the let Timer = null 
    // closure 
    return  function () {
         IF (Timer) { 
            the clearTimeout (Timer) 
        } 
        Timer = the setTimeout (Fn, Delay) 
    } 
} 

// Rewrite code 
... 
 test.onkeyup $ = Debounce (autosearch, 1000 ); 
...

Operating results once again that we want the results:

Throttling

High-frequency event is triggered, but only once within n seconds, it will dilute the throttle perform a function of frequency.
Ideas: every judge whether there is a trigger event delay function currently awaiting execution.

Or the above example: If a user pain free eggs, has been pressing the keyboard is not doing nothing, so long as she again pressed the keyboard in 1 second, will never have the resulting output, but we also want at a time after the interval it gives feedback

Use the same method with debounce. Code logic is similar. Over time interval ms interval is executed when triggered. Otherwise not executed. if the judgment is guaranteed to call setTimeout after the last event trigger, so to clear each time the timer interval not to re-start the timer. The function is performed upon reaching the time interval. Code logic is very simple, needless to say, I believe that smart you are self-explanatory.

function throttle(fn,interval){
    var last;
    var timer;
    var interval=interval||200;
    return function(){
        var th=this;
        var args=arguments;
        var now=+new Date();
        if(last&&now-last<interval){
            clearTimeout(timer);
            timer=setTimeout(function(){
                last=now;
                fn.apply(th,args);
            },interval);
        } The else{ 
            Last = now; 
            fn.apply (TH, args); 
        } 
    } 
} 

// Rewrite code 
... 
 $ test.onkeyup = Throttle (autosearch, 1000 ); 
...

The result is that we want to run the results (no matter what the input text box, not one second output a result):

 

rxjs implementation

Rxjs use, easier to use (to remember to install or incorporated rxjs oh)
using debounceTime (stabilization) and throttleTime (throttle) operator, convection be limiting, and then subscribe to comply with the rules of the stream, i.e., the output data of the desired can,
rxjs can refer to the official documentation. https://cn.rx.js.org/
can also view the interactive map Rx observed:
debounceTime:  https://rxmarbles.com/#debounceTime
throttleTime: HTTPS: // rxmarbles. com / # throttleTime
example:

<head>
    <script src="https://cdn.bootcss.com/rxjs/6.0.0-alpha.3/Rx.min.js"></script>
</head>

<body>
防抖:<input type="text" placeholder="简拼/汉字/三字码" id="debounce"/><br/><br/>
节流:<input type="text" placeholder="简拼/汉字/三字码" id="throttle"/>
<script>
    var $debounce = document.getElementById('debounce');
    var $throttle = document.getElementById('throttle');
    const debounce$ = Rx.Observable.fromEvent($debounce, 'input');
    const throttle = Rx.Observable.fromEvent($throttle, 'input');
    // 节流
    debounce$
        .debounceTime(1000)
        .subscribe(function (e) {
            var value = e.target.value;
            console.log('防抖:'+value)
        });
    // 防抖
    throttle
        .throttleTime(1000)
        .subscribe(function (e) {
            var value = e.target.value;
            console.log('节流:'+value)
        });
</script>
</body>

result:



 

Guess you like

Origin www.cnblogs.com/darkbluelove/p/11418106.html