Last active
          March 3, 2024 03:20 
        
      - 
      
 - 
        
Save rpemberton/b15a206f453ff233830f3183e4ac371a to your computer and use it in GitHub Desktop.  
    Debounce with requestAnimationFrame
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | // Useful for debouncing callbacks to mousemove, resize, scroll event listeners | |
| function debounce(fn) { | |
| let raf; | |
| return (...args) => { | |
| if (raf) { | |
| console.log('debounced'); | |
| return; | |
| } | |
| raf = window.requestAnimationFrame(() => { | |
| fn(...args); // run useful code | |
| raf = undefined; | |
| }); | |
| }; | |
| } | |
| function handleMouseMove(e) { | |
| console.log('handleMouseMove', e); | |
| } | |
| const debouncedHandleMouseMove = debounce(handleMouseMove); | |
| document.addEventListener('mousemove', debouncedHandleMouseMove); | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment