Last active
March 5, 2021 05:13
-
-
Save zhongyangxun/676b62f1344c7c3572e40a0dd259ee1f to your computer and use it in GitHub Desktop.
JavaScript debounce function.
This file contains 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
function debounce(func, wait = 200, immediate) { | |
let timeout = null; | |
let context = null; | |
let args = null; | |
let previous = null; | |
let result = null; | |
function later() { | |
var passed = Date.now() - previous; | |
if (passed < wait) { | |
timeout = setTimeout(later, wait - passed); | |
} else { | |
timeout = null; | |
if (!immediate) func.apply(context, args); | |
} | |
} | |
return function (...rest) { | |
context = this; | |
args = rest; | |
previous = Date.now(); | |
if (!timeout) { | |
timeout = setTimeout(later, wait); | |
if (immediate) result = func.apply(context, args); | |
} | |
return result; | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment