On the anti-shake and throttling of JS

On the anti-shake and throttling of JS

Foreword: Before understanding anti-shake and throttling, let's understand the focus events and keyboard events

1. Focus event (focus, blur, input)

  • FocusEvent

    Focus events are mainly used for form elements and hyperlinks. The click or tab can be used to switch the focus distance. When the input focus is triggered, the focus is triggered when the focus is lost.

    • foucs is the focal length of the focal length
    • blur loses focus
    • The relatedTarget in the event object is the last object that has lost focus
    <form>
        <input type="text">
        <input type="checkbox">
        <input type="checkbox">
        <select>
            <option>aaaa</option>
            <option>bbb</option>
            <option>aaaa</option>
            <option>aaaa</option>
            <option>aaaa</option>
        </select>
    </form>
    <a href="#">超链接</a>
    <script>
                var form=document.querySelector("form");
        var input=document.querySelector("input");
        input.addEventListener("focus",focusHandler);
        input.addEventListener("blur",focusHandler);

        // 获取单选按钮
        var checkboxs=document.querySelectorAll("[type=checkbox]");
        for(var i=0;i<checkboxs.length;i++){
            checkboxs[i].addEventListener("focus",focusHandler)
        }

        // 获取下拉列表
        var select=document.querySelector("select");
        select.addEventListener("focus",focusHandler);

        //获取超链接
        var a=document.querySelector("a");
        a.addEventListener("focus",focusHandler)

        function focusHandler(e){
            console.log(e.target,e);
            if(e.type==="focus"){
                e.target.style.outline="1px solid purple"
                e.target.style.outlineOffset="0px";
            }else if(e.type==="blur"){
                e.target.style.outline="1px solid rgba(255,0,0,0)";
                e.target.style.outlineOffset="5px";
            }
        }


    </script>

Defocus and focus are mainly used to judge form validation

        // input  输入事件主要用于文本框和多行文本框

        var input=document.querySelector("input");
        input.addEventListener("input",inputHandler);

        function inputHandler(e){
           console.log(e);
        // e.data: "s"  本次输入的内容
        // e.isComposing: false  输入法是否启动
        // e.inputType 输入的类型
        // insertCompositionText 输入插入
        // historyUndo 历史返回
        // insertText  插入文本
        // deleteContentBackward 退格删除(删除前一个)
        // deleteContentForward  delete删除(删除后一个)
        // deleteByCut 剪切删除
        // insertFromPaste 粘贴插入
      }

Second, KeyboardEvent keyboard event

    <div></div>
    <script>
        var bool=false
        // 按键是侦听document
        document.addEventListener("keydown",keyHandler);
        document.addEventListener("keyup",keyHandler);
        // keydown不单纯在按下时存在,一直按着也会触发
        function keyHandler(e){
            if(e.type==="keydown"){
                // 希望在什么地方加开关,这个开关指锁定这个位置
                if(!bool){
                    console.log(e.type,e.keyCode);
                }
                bool=true;
                return;
            }else{
                bool=false;
            }
            console.log(e.type,e.keyCode);
            // e.code: "KeyJ"  键名
            // key: "j"   键名
            // keyCode: 74  键码
            // which   键码
            // 左 上 右 下  37,38,39,40
        }

1. Throttling

When the text box is input, if it is judged every time it is input, it will cause too low efficiency. We let it be verified every interval. It means to trigger the event continuously but only execute the function once in n seconds.

Implementation principle

Set an attribute for input, when the event is triggered for the first time, the attribute value is false, then execute down, get the value of input after 500 milliseconds, and delete the value of ids; when the second input, when 500 milliseconds have not yet arrived , Ids is true, then jump out directly without getting value. In 500 milliseconds, the function is executed only once.

Throttling timer writing:

<input type="text" name="text" id="user">
<script>
	init();
	function init(){
	    var user=document.getElementById("user");
	     user.addEventListener("input",inputHandler);
	}
	function inputHandler(e){
	    //判断,如果input.ids为false,则往下执行
	    if(this.ids) return;
	    //500毫秒后,执行showValue函数,同时删除ids的值
	    this.ids=setTimeout(function(elem){
	    	//因为定时器函数会改变this指向,这里将this以参数的形式传进来
	        clearTimeout(elem.ids);
	        elem.ids=null;
	        showValue(elem.value);
	    },500,this);
	}
	//打印出input的值
	function showValue(txt){
	    console.log(txt);
	}
</script>

Throttling timestamp writing:

<input type="text" name="text" id="user">
<script>
	init();	
	function init() {
	    var user = document.getElementById("user");
	    user.addEventListener("input", inputHandler);
	}
	var lastTime=0;
	function inputHandler(e) {
	    //每次触发事件获取当前时间
	   let nowTime=new Date().getTime();
	   //若时间间隔大于500毫秒,则执行代码
	   if(nowTime-lastTime>500){
	       //重新计时
	       lastTime=nowTime;
	       showValue(this.value);
	   }
	}
	//打印出input的值
	function showValue(txt) {
	    console.log(txt);
	}
</script>

2. Anti-shake

Anti-shake means that the function can only be executed once within n seconds after the trigger event. If the event is triggered again within n seconds, the function execution time will be recalculated.
The keydown event is triggered when the keyboard is pressed. If the keyboard is pressed all the time, this event will be triggered all the time. We do not want to execute the function as frequently as the event continues to be triggered. In this case, anti-shake is a better solution.

=== Realization principle:

When the keydown event is continuously triggered, the event handler is only called once after stopping the key press for 500 milliseconds. That is to say, the event handler function handle has not been executed during the continuous triggering of the keydown event.

Throttling and anti-shake are similar. Based on the above throttling, we should form the following code

<input type="text" name="text" id="user">
<script>
	init();
	function init() {
	    var user = document.getElementById("user");
	    user.addEventListener("input", inputHandler);
	}
	var ids=null;
	function inputHandler(e) {
		//每次输入,把前面的定时器清除,重新开启定时器
	    if(ids !== null) clearTimeout(ids);
	    ids=setTimeout(function(){
	        showValue(this.value);
	    },500)
	}
	//打印出input的值
	function showValue(txt) {
	    console.log(txt);
	}
</script>

=== Anti-shake package:

 function debounce(fn, wait) {
    var timeout = null; //定义一个定时器
    return function () {
        if (timeout !== null)
            clearTimeout(timeout); //清除这个定时器
        timeout = setTimeout(fn, wait);
    }
}
// 处理函数
function handle() {
    console.log(Math.random());
}
// 侦听事件
document.addEventListener("keydown", debounce(handle, 1000));

The difference between anti-shake and throttle?

  • Throttling is to change multiple executions to execute at intervals
  • Anti-shake is to turn multiple executions into the last execution

Guess you like

Origin www.cnblogs.com/my12-28/p/12655481.html