Anti-shake function and a function of the throttle knowledge summary

What is the function of image stabilization?

Callback is triggered in the event n seconds, and then, if this has been triggered in n seconds, it will re-calculate the execution time delay function.

For example: take the elevator when the elevator is detected if people come in (the triggering event), there will be more wait 10 seconds, then if someone comes in (repeat trigger event within 10 seconds), then the elevator will wait 10 seconds more .

Why do we need anti-shake function

  • onResize , the Scroll , mouseMove , the MouseHover , etc., if the trigger several times within a short time, no limit, it is possible to perform dozens of times within one second, hundreds of times, if you perform other functions inside these functions, in particular the implementation of DOM operations functions (browser DOM is very time consuming operation performance), it is not only a waste of computer resources, but also reduce the running speed, or even cause the browser stuck, crashes.

  • Repeat short time ajax calls will not only cause confusion data relationships, can also cause network congestion, increasing the pressure on the server.

There have been in actual combat scenarios

Continuous event, simply trigger a callback scenarios:

  • In doing pc of the adaptive time, by rewriting onresize events, dynamically changing the size rem to achieve, you can use the anti-shake functions, such as user adjust the page and then trigger this function; the window just after the adjustment is completed, the window size is calculated . Prevent duplicate rendering.
  • Achieve magnifying glass feature, use the zoom function to achieve mousemove this api;
  • Search search input box. Just finished the last user input, then sends a request

Realization of ideas image stabilization

We need a setTimeout to assist in achieving the code delay operation to be performed.

If the method is triggered repeatedly, put the last delay execution of the code recorded with clearTimeout cleared to restart timing.

If during the timed event is not triggered again, and so the delay time expired, the object code is executed.

Code for image stabilization function

And in order to facilitate mass participation issues and a callback function call fn anti-shake function, we should use closures to solve these problems.

function debounce(fn,wait){
    var timer = null;
    return function(){
    	var _this = this;
    	var args = arguments;  // 取debounce执行作用域的this
        if(timer !== null){
            clearTimeout(timer);
        }
        timer = setTimeout(function(){
        	fn.apply(_this,agrs);// 用apply指向调用debounce的对象,相当于_this.fn(args);
        },wait);
    }
}
    
function handle(){
    console.log(Math.random());
}
    
window.addEventListener("onresize",debounce(handle,1000));

What is the function of the throttle?

Every so often, only once function

For example: train or subway, when security over a certain time (e.g., 10 seconds), allows only one passenger entrance through security to meet the security personnel to complete security screening;

Why throttle function?

And the reason is the same anti-shake function

Function throttle combat scene

  • Rolling load, load more or roll the bottom of the monitor
  • High-frequency clicks submit, the form submitted to repeat

Throttle function realization of ideas

The main idea is realized through setTimeout timer; or by practice to set stamp;

  • Timestamp: By this magnitude versus time than the execution time difference between the time and the execution time interval, determines whether to execute the function. If the difference is greater than the time interval, then immediately perform a function. And update the last execution time.
  • Timer: One thing to note is: Empty timer delay after the completion of the implementation of fn, this time timer is false, throttle trigger can enter the timer

Code for throttling function

  • Timestamp
function throttle(fn,wait){
	var pre = Date.now();
	// 使用闭包返回一个函数并且用到闭包函数外面的变量pre
	return function(){
		var _this = this;
		var args = arguments;
		
		var now = Date.now();
		if(now-pre >= wait){
			fn.apply(_this,args);
			pre = now;
		}
	}
}
function handle(){
    console.log(Math.random());
}
window.addEventListener("mousemove",throttle(handle,1000));
  • Timer
function throttle(fn,wait){
	var timer;
	return function(){
		var _this = this;
		var args = arguments;
		//这时候如果timer存在,不给执行
		if(timer){
			return;
		}
		if(!timer){
			timer = setTimeout(funciton(){
				fn.apply(_this,args);
				timer = null; // 在delay后执行完fn之后清空timer,此时timer为假,throttle触发可以进入计时器
			},wait)
		}	
	}
}
function handle(){
    console.log(Math.random());
}   
window.addEventListener("mousemove",throttle(handle,1000));

Image stabilization function and a throttle function A comparison between

  • Same point:

    • Can be achieved by setTimeout
    • The purpose is to reduce the frequency of callbacks.
  • difference:

    • Function Image Stabilization concerned about the incident triggered a certain time in a row only once in the last execution, while focusing on the throttle function is performed only once in a period of time.
Published 17 original articles · won praise 0 · Views 574

Guess you like

Origin blog.csdn.net/weixin_43827779/article/details/104840875