节流(throttle) 就是说在短时间内,如果快速重复的点击,无法执行请求

  1. <button id="btn"></button>
  2. <script>
  3. function throttle(fn,delay){
  4. let timer;
  5. return function(){
  6. let self = this
  7. if(timer) return;
  8. timer = setTimeout(()=>{
  9. fn.apply(self,arguments)
  10. timer = null
  11. },delay)
  12. }
  13. }
  14. function fn(){
  15. console.log('测试节流')
  16. }
  17. document.querySelector("#btn").addEventListener('click',throttle(fn,1000))
  18. </script>

立即执行

  1. //防抖(合并版)
  2. function debounce_merge(fn, wait = 500, isImmediate = false) {
  3. var timerId = null;
  4. var flag = true;
  5. return function () {
  6. var context = this
  7. var args = arguments
  8. if(timerId) return false;
  9. if (isImmediate) {
  10. if (flag) {
  11. fn.apply(context, args)
  12. flag = false
  13. }
  14. timerId = setTimeout(function () {
  15. flag = true
  16. }, wait)
  17. } else {
  18. timerId = setTimeout(function () {
  19. fn.apply(context, args)
  20. }, wait)
  21. }
  22. }
  23. }