防抖: 一定时间内频繁触发一个事件则不会执行对应的操作, 只有大于这个时间再次触发才会执行 action
- function _debounce(func, wait) {
- // 一上来就执行了, this 是 window
- let timer = null;
- let context, args;
- return function () {
- // 返回的函数 this 才是 oBox
- context = this;
- args = arguments;
- clearTimeout(timer);
- timer = setTimeout(function () {
- func.apply(context, args);
- }, wait);
- }
- }
- let oBox = document.querySelector('#root');
- oBox.onmousemove = _debounce(function () {
- console.log(1);
- }, 500);
- // 函数节流
- let canRun = true;
- document.getElementById("root").onmousemove = function () {
- if (!canRun) {
- return;
- }
- // 马上设置 false, 在 300ms 内触发事件会直接 return
- canRun = false;
- setTimeout(function () {
- console.log(2);
- // 300ms 后可以继续了
- canRun = true;
- }, 300);
- };
来源: http://www.bubuko.com/infodetail-2745460.html