The distal js - throttling function

Disclaimer: This article is a blogger original article, shall not be reproduced without the bloggers allowed. https://blog.csdn.net/qq_36251118/article/details/88854242

Method binding when resize, scroll, hover and other js trigger event will be called frequently, resulting in page performance issues, so we use the throttle function to solve this problem decision

	//scroll方法中当间隔时间大于2s,do somthing执行一次
	window.addEventListener('scroll',function(){
	    var timer ;//使用闭包,缓存变量
	    var startTime = new Date();
	    return function(){
	        var curTime = new Date();
	        if(curTime - startTime >= 2000){
	            timer = setTimeout(function(){
	                console.log('do somthing')
	            },500);
	            startTime = curTime;
	        }
	 
	    }
	}());
	

	//ES6
	/**
     * 节流函数
     * @param fn Function 触发事件后需要执行的函数
     * @param delay String  间隔时间 ms
     * */
    delayScrollFunc(fn, delay) {
      const now = new Date().getTime();
      if (now - this.lastScrollCall < delay) return;
      this.lastScrollCall = now;
 
      setTimeout(() => {
        fn();
      }, 60); // 在实际项目中,我发现这里再延迟一点时间执行效果更好(针对监听scroll)
    },

Guess you like

Origin blog.csdn.net/qq_36251118/article/details/88854242