Throttle function summary

Throttling function
when calling window.onresize event, if the operation is extremely frequent operation DOM consumption performance, so in this case the function can be throttled by a timer.
The basic idea behind the throttle function is:
Some code execution can not be repeated without interruption.
The first call to the function, create a timer, run the code after a specified interval.
The second function is called once it clears before the timer and set up another. If executed before a timer, this operation would not make any sense.
However, before a timer if not already done so, in fact, it will be replaced with a new timer.
The purpose is only a request to perform a function stopped after some time to execute. The following is the basic form of the model:

var processor = {
	timeoutId: null,
	//实际进行处理的方法
	performProcessing: function(){
		//实际执行的代码
	},
	//初识处理调用的方法
	process: function(){
		clearTimeout(this.timeoutId);
		var that = this;
		this.timeoutId = setTimeout(function(){
			that.performProcessing();
		},100)
	}
}
processor.process();

process () initialize any treatment that must be invoked.
performProcessing (actually process to be completed).

This mode may be used Throttle () function to simplify, this timer function can be automatically set and clear, the following example:

function throttle(method,context){
	clearTimeout(method.tId);
	method.tId = setTimeout(function(){
		method.call(context);
	},100)
}

Throttle () function accepts two arguments:

  1. Function method to be executed
  2. In which the scope of execution

Above this function first clears any previously set timer.
Look at the specific application function throttling:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>函数节流</title>
</head>
<body>
    <div id='root' style="background: red;">
       123
    </div>
    <script>
        var root = document.getElementById('root');
        function reszie(){
            console.log('offsetWidth',root.offsetWidth);
            root.style.height = root.offsetWidth + 'px';
            root.style.background = 'red';
        }
        window.onresize = function(){
            throttle(reszie);
        }
        //method 要执行的函数
        //context 在哪个作用域
        function throttle(method,context){
            clearTimeout(method.tId);
            method.tId = setTimeout(function(){
                method.call(context);
            },1000)
        }
    </script>
</body>
</html>

Guess you like

Origin blog.csdn.net/boysky0015/article/details/94485684