You do not know the secret of the throttle function

Throttle function

  • Then on an anti-shake function, a closer look at the definition of anti-shake function can not read

    • When the function is in a very small period of time is frequently triggered only when the time is accumulated to a certain extent, it will execute the function once
  • In fact, as a function of the throttle daily life in a not tighten the faucet drip drop by drop

  • Let's use code to simulate what once immediately knock the faucet drip drop scene

  // 取一个水桶
  var oShuiTong = document.getElementById('shuitong');
	// 滴水函数
	function diShui() {
	  // 水桶中增加一滴水
	  oShuiTong.innerText = parseInt(oShuiTong.innerText) + 1;
	}
	// 一个神奇的水龙头
  var oLongTou = document.getElementById('longtou');
	// 敲一下水龙头就滴下一滴水
	oLongTou.onclick = diShui
  • Life is full of well-known Jie bear children, and if they find such a magical faucet, just the bear and gifted children, the moment can tap faucet 1000! Simulation code as follows
	for (var i = 0; i < 1000; i ++) {
	  oLongTou.click();
	}
  • In an instant more than a bucket of water poured. . This is terrible

  • So we are back to reality, only a certain amount of water accumulated on the faucet, only dropping a drop of water, which at a certain time before the operation can be performed once the package as a function of the abstract, more versatile

	function throttle(fn, waitTime) {
	  var lastTime = 0;
	  return function () {
	    // 获取当前时间
	    var nowTime = new Date().getTime();
	    if (nowTime - lastTime > waitTime) {
	      fn();
	      lastTime = nowTime;
	    }
	  }
	}
  • A second drop of water dripping faucet
	oLongTou.onclick = throttle(diShui, 1000);
  • Function throttling scenarios

    • Window adjustment (resize)

    • Page scrolling (scroll)

    • Click mad rush to buy (mousedown)

Published 49 original articles · won praise 29 · views 1895

Guess you like

Origin blog.csdn.net/Brannua/article/details/104756177