We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
原理:你尽管触发事件,但是我一定在事件触发 n 秒后才执行,如果你在一个事件触发的 n 秒内又触发了这个事件,那我就以新的事件的时间为准,n 秒后才执行,总之,就是要等你触发完事件 n 秒内不再触发事件,才执行;
function debounce(fn, timeout){ timeout = timeout || 200; var timer = null; return function(){ clearTimeout(timer); timer = setTimeout(fn, timeout) } }
function debounce(fn, timeout){ timeout = timeout || 200; var timer = null; return function(){ clearTimeout(timer); timer = setTimeout(fn.bind(this), timeout) } }
function debounce(fn, timeout){ timeout = timeout || 200; var timer = null; return function(){ var context = this; var args = arguments; clearTimeout(timer); timer = setTimeout(function(){ fn.apply(context, args) }, timeout) } }
事件触发后立刻执行函数,然后等到停止触发 n 秒后,才可以重新触发执行。
function debounce(fn, timeout, immediate){ timeout = timeout || 200; var timer = null; return function(){ var context = this; var args = arguments; clearTimeout(timer); if(immediate){ var callNow = !timer; if(callNow){ fn.apply(context, args) } timer = setTimeout(function(){ timer = null; }, timeout) }else{ timer = setTimeout(function(){ fn.apply(context, args) }, timeout) } } }
function debounce(fn, timeout, immediate){ timeout = timeout || 200; var timer = null; var result; return function(){ var context = this; var args = arguments; clearTimeout(timer); if(immediate){ var callNow = !timer; if(callNow){ result = fn.apply(context, args) } timer = setTimeout(function(){ timer = null; }, timeout) }else{ timer = setTimeout(function(){ fn.apply(context, args) }, timeout) } return result; } }
function debounce(fn, timeout, immediate){ timeout = timeout || 200; var timer = null; var result; var debounced = function(){ var context = this; var args = arguments; clearTimeout(timer); if(immediate){ var callNow = !timer; if(callNow){ result = fn.apply(context, args) } timer = setTimeout(function(){ timer = null; }, timeout) }else{ timer = setTimeout(function(){ fn.apply(context, args) }, timeout) } return result; } debounced.cancel = function(){ clearTimeout(timer); timer = null; } }
The text was updated successfully, but these errors were encountered:
No branches or pull requests
防抖
实现
完善-this指向
完善-参数传递
需求--立即执行
事件触发后立刻执行函数,然后等到停止触发 n 秒后,才可以重新触发执行。
返回值
取消
JavaScript专题之跟着underscore学防抖
The text was updated successfully, but these errors were encountered: