关于javascript:函数防抖和节流

11次阅读

共计 391 个字符,预计需要花费 1 分钟才能阅读完成。

防抖与节流

函数防抖

在函数被触发后提早某个时间段后触发,如果在该时间段内再次触发,则从新计时

简略实现

// 防抖函数
function debounce(fun, delay) {
  let record = null
  return (...content) => {if (record) {clearTimeout(record)
    }
    record = setTimeout(() => {fun(...content)
    }, delay)
  }
}

函数节流

在一个时间段内一个函数屡次被触发,只有一次会失效

简略实现

// 节流函数
function throttle(fun, delay) {
  let record = null
  return (...content) => {if (!record) {record = setTimeout(() => {fun(...content)
        clearTimeout(record)
        record = null
      }, delay)
    }
  }
}

正文完
 0