防抖

防抖是让一个函数在一段时间间隔内没有调用,才开始执行被调用

  1. function debounce(func, delay){
  2. // set timer as null
  3. let timer = null;
  4. return function() {
  5. // if timer is not null, wipe it
  6. // if you input a value during the timer, wipe the last time
  7. // and start to time again
  8. if(timer) clearTimeout(timer)
  9. timer = setTimeout(() => {
  10. // change the direction of this
  11. func.call(this)
  12. }, delay)
  13. }
  14. }
  15. // React hooks 版本
  16. const useDebounce = (func: any, delay: number) => {
  17. const timer = React.useRef<any>(null);
  18. const debounce = React.useCallback(() => {
  19. if(timer.current) clearTimeout(timer.current)
  20. timer.current = setTimeout(() => {
  21. func();
  22. }, delay)
  23. }, [func, delay])
  24. return debounce;
  25. }

节流

节流是让一个函数无法在很短的时间间隔内被多次调用。意思就是一个函数被调用了后,得让它歇一下,等它歇完了(等一定的时间间隔之后),才能被再次调用。

  1. function throttle(func, delay){
  2. let previous = 0
  3. return function() {
  4. let now = Date.now()
  5. if(now-previous > delay){
  6. func.call(this)
  7. previous = now
  8. }
  9. }
  10. }
  11. // react hooks function
  12. const useThorttle = (func: any, delay: number) => {
  13. const timer = React.useRef<any>(-1)
  14. const throttle = React.useCallback(() => {
  15. if(timer.current > -1) return null;
  16. timer.current = setTimeout(() => {
  17. func();
  18. timer.current = -1;
  19. clearTimeout(timer.current);
  20. }, delay)
  21. }, [func, delay])
  22. return throttle
  23. }
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7. <title>Document</title>
  8. </head>
  9. <body>
  10. <input type="text">
  11. <div style="height: 1000px;"></div>
  12. </body>
  13. <script>
  14. const input = document.querySelector('input');
  15. input.oninput = debounce(function () {
  16. console.log(this.value);
  17. }, 1000)
  18. function debounce(func, delay) {
  19. let timer = null
  20. return function () {
  21. if (timer) clearTimeout(timer)
  22. timer = setTimeout(() => {
  23. func.call(this)
  24. }, delay)
  25. }
  26. }
  27. window.onscroll = throttle(function () {
  28. console.log('page scroll');
  29. }, 1000);
  30. // window.onscroll = function () {
  31. // console.log('page scroll');
  32. // };
  33. function throttle(func, delay) {
  34. let previous = 0;
  35. return function () {
  36. let now = Date.now();
  37. if (now - previous > delay) {
  38. func.call(this);
  39. previous = now;
  40. }
  41. }
  42. }
  43. </script>
  44. </html>