防抖 & 节流

52 阅读1分钟

**防抖原理:**执行一个函数,会等待n秒,只有在n秒之后不再有操作,事件才会真正被触发。

function debounce(func, wati) {  let timeout  return function () {    const context = this,      args = arguments    clearTimeout(timeout)    timeout = setTimeout(function () {      func.apply(context, args)    }, wati)  }}

**节流原理:**触发一个事件,每隔一段时间,只执行一次该事件。

// 时间戳方式
function thorttle(func, wait) {  let previous = 0  return function () {    let now = +new Date()    const context = this,      args = arguments    if (now - previous > wait) {      func.apply(context, args)      previous = now    }  }}
// 定时器方式
function thorttle(func, wait) {  let timeout  return function () {    const context = this,      args = arguments    if (!timeout) {      timeout = setTimeout(function () {        timeout = null        func.apply(context, args)      }, wait)    }  }}