Home >Web Front-end >JS Tutorial >Detailed explanation of js high-performance function anti-shake and throttling

Detailed explanation of js high-performance function anti-shake and throttling

小云云
小云云Original
2018-03-17 15:01:571815browse

Function throttling means that the js method will only run once within a certain period of time. Function anti-shake: means that when triggered frequently, the code will only be executed once when there is enough free time. This article mainly shares with you the detailed explanation of js high-performance function anti-shake and throttling. I hope it can help everyone.

1. Function throttling (throttle)

1. The purpose of function throttling
For example, DOM operations require more memory and CPU time than non-DOM interactions. Attempting to perform too many DOM-related operations in succession can cause the browser to hang and sometimes even crash. This is especially likely to happen when using the onresize event handler in IE. When the browser is resized, the event will be triggered continuously. If you try to perform DOM operations inside the onresize event handler, its high frequency of changes may crash the browser. For another example, for a common search function, we usually bind the keyup event and search every time the keyboard is pressed. But our purpose is mainly to search every time we enter some content. In order to solve these problems, you can use timers to throttle functions.
2. Principle of function throttling
Some codes cannot be executed continuously and repeatedly without interruption. The first time the function is called, a timer is created to run code after a specified interval. When the function is called a second time, it clears the previous timer and sets another one. If the previous timer has already been executed, this operation has no meaning. However, if the previous timer has not yet been executed, it is actually replaced with a new timer. The purpose is to execute the function only after the request to execute it has been stopped for some time.

3. Basic mode of function throttling

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

4. Liezi

<!DOCTYPE html>
<html lang="zh-CN">
<head>  
	<meta charset="utf-8">
    <title></title>  
</head>  
<body>  	
	<input id="search" type="text" name="search">
<script>

	function queryData(text){
	  console.log("搜索:" + text);
	}
	var input = document.getElementById("search");
	input.addEventListener("keyup", function(event){
	  	throttle(queryData, null,500,this.value,1000);
	});
	        
function throttle(fn,context,delay,text,mustApplyTime){
  clearTimeout(fn.timer);
  fn._cur=Date.now();  //记录当前时间
 
  if(!fn._start){      //若该函数是第一次调用,则直接设置_start,即开始时间,为_cur,即此刻的时间
    fn._start=fn._cur;
  }
  if(fn._cur-fn._start>mustApplyTime){        //当前时间与上一次函数被执行的时间作差,与mustApplyTime比较,若大于,则必须执行一次函数,若小于,则重新设置计时器
     fn.call(context,text);
     fn._start=fn._cur;
  }else{
    fn.timer=setTimeout(function(){
    fn.call(context,text);
    },delay);
  }
}
</script>
</body>  
</html>

Detailed explanation of JavaScript throttling function Throttle

Talk about JS Function throttling

2. Function debounce

Before explaining this function, let’s look at an example: the registration page requires verification of the phone number. At this point, what we may think of is to listen to the keypress event and then verify it. This method itself is correct, but if the user quickly enters a series of mobile phone numbers , 11 requests will be triggered in an instant, which is undoubtedly not what we want. What we want is to trigger the verification request when the user stops typing. At this time, function anti-shake can help us.

function debounce(func, wait, immediate) {
    var timeout; // 持久化一个定时器
     // 闭包函数可以访问timeout
    return function() {
    	 // 通过 this 和 arguments 获得函数的作用域和参数
        var context = this, args = arguments;
        var later = function() {
            timeout = null;
            if (!immediate) func.apply(context, args);
        };
        var callNow = immediate && !timeout;
        clearTimeout(timeout); // 如果事件被触发,清除timer并重新开始计时
        timeout = setTimeout(later, wait);
        if (callNow) func.apply(context, args);
    };
};

The parameter function is the function that needs to be anti-shake; the parameter wait is the time to wait, in milliseconds; if the immediate parameter is true, the debounce function will execute the function immediately when it is called, and You don't need to wait until the wait time. For example, you can use this parameter to prevent multiple clicks when clicking the submit button.

Lie Zi:

<!DOCTYPE html>
<html lang="en" >
<head>
<meta charset="UTF-8">
<title>函数防抖与节流 </title>
</head>
<body>
	<form class="form-cnt" action="" method="">
			<input type="text" value="" id="tel"/>
	</form>
	<script type="text/javascript" src="js/jQuery-2.1.4.min.js" ></script>
<script>
function debounce(func, wait, immediate) {
    var timeout;
    return function() {
        var context = this, args = arguments;
        var later = function() {
            timeout = null;
            if (!immediate) func.apply(context, args);
        };
        var callNow = immediate && !timeout;
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
        if (callNow) func.apply(context, args);
    };
};

function checkTel(){
	var val = $("#tel").val();  
	 var  re = new RegExp("(^1[3|4|5|7|8][0-9]{9}$)");  
	if(re.test(val)){  
	  console.log("结果:格式正确");  
	}else{  
	    console.log("结果:格式错误");  
	}  
}  
var lazyQuery = debounce(checkTel, 300);
$("#tel").on("keypress",lazyQuery);  
</script>
</body>
</html>


This effect can be seen to be triggered 6 times instead of 11 times

三.Application scenarios

(1).Function throttling(throttle)
1. Frequent mousemove/keydown, such as high-frequency mouse movement, game shooting
2. Search Lenovo (keyup) )
3. Progress bar (we may not need to update the progress frequently)
4. Dragover, etc.
5. High-frequency clicks, draws, etc. (haha, evil)

(2). Function debounce
1. scroll/resize event
2. Continuous text input, ajax verification/keyword search

The above is the detailed content of Detailed explanation of js high-performance function anti-shake and throttling. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn