未来软件工作室

    未来软件工作室论坛

    • Login
    • Search
    • Categories
    • Recent
    • Tags
    • Popular
    • Users
    • Groups
    • 官网

    (进阶)浏览器优化之防抖与节流

    技术分享
    1
    1
    17
    Loading More Posts
    • Oldest to Newest
    • Newest to Oldest
    • Most Votes
    Reply
    • Reply as topic
    Log in to reply
    This topic has been deleted. Only users with topic management privileges can see it.
    • 20191564113
      张保林 管理员 last edited by

      浏览器对事件的优化

      一般我们屏幕的帧率是每秒60帧,也就是60fps,但是某些事件触发的频率超过了这个数值,比如 wheel, mousewheel,mousemove,pointermove,touchmove,这些连续性的事件一般每 秒会触发60~120次,假如每一次触发事件都将事件发送到主线程处理,由于屏幕的刷新速率相对 来说较低,这样使得主线程会触发过量的命中测试以及JS代码,使得性能有了没必要的损耗。 出于优化的目的,浏览器会合并这些连续的事件,延迟到下一帧渲染是执行,也就是 requestAnimationFrame之前。

      防抖

      function debounce(callback,wait){
      	let timerId = null;
      	return function(event){
      		if (timerId !== null){
      			clearTimeout(timerId);
      		}
      		timerId = setTimeout(()=>{
      			callback.call(this,event);
      			timerId = null;
      		},wait)
      	}
      }
      	document.querySelector('input').addEventListener('keydown',debounce(function(e){
      	console.log(this.value)
      },500))
      
      

      节流

      function throttle(callback,wait){
      	let start = 0;
      	return function(){
      		let now = Date.now();
      		if (now - wait > start){
      			callback.call(this,event);
      			start = now;
      		}
      	}
      }
      window.addEventListener('scroll',throttle(function(e){
      	console.log(Date.now());
      },500))
      
      
      1 Reply Last reply Reply Quote 0
      • First post
        Last post
      Powered by NodeBB | Contributors