防抖节流 附带vue防抖节流实例(防抖会先触发再防抖)
<html> <head> <script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script> <style> #onMouseover { width: 400px; height: 400px; background-color: #eee; } </style> </head> <div id="onMouseover"></div> <body> <script> function count() { console.log(1) } // 防抖 先立即执行,再等2秒 function debounce(func, wait) { let timeout return function () { if (timeout) { clearTimeout(timeout) } let callNow = !timeout timeout = setTimeout(() => { timeout = null }, wait) if (callNow) { func.apply(this) } } } const onMouseDiv = document.getElementById("onMouseover") // onMouseDiv.onmousemove = debounce(count, 2000) // wait时间后执行 export const debounceWait = (func, wait = 200) => { let timer = null; return function () { if (timer) clearTimeout(timer) timer = setTimeout(() => { func.apply(this, arguments); timer = null }, wait) } } // 节流 通过setTimeout // function throttle(func, wait) { // let timeout // return function () { // if (!timeout) { // timeout = setTimeout(() => { // timeout = null // func.apply(this) // }, wait) // } // } // } // 节流 通过时间长,使用移动端 function throttle(func, wait) { let prev = 0 return function () { let now = Date.now() if (now - prev > wait) { func.apply(this) prev = now } } } onMouseDiv.onmousemove = throttle(count, 2000) </script> </body> </html>
//第一步:vue中使用防抖节流,公用js库语法。 export const debounce = (func, wait) => { let timeout; return function () { if (timeout) { clearTimeout(timeout); } const callNow = !timeout; timeout = setTimeout(() => { timeout = null; }, wait); if (callNow) { func.apply(this); } }; }; export const throttle = (func, wait) => { let prev = 0; return function () { const now = Date.now(); if (now - prev > wait) { func.apply(this); prev = now; } }; };
//第二步 vue页面中使用防抖、节流方法 import { debounce, throttle } from '@/components/debounceThrottle/index'; test: debounce(function() { this.pay(); }, 1000), pay() { console.log('pay'); }