Skip to content

Instantly share code, notes, and snippets.

@lushijie
Last active February 19, 2016 04:16
Show Gist options
  • Save lushijie/20a7c9379a1baafb0b8f to your computer and use it in GitHub Desktop.
Save lushijie/20a7c9379a1baafb0b8f to your computer and use it in GitHub Desktop.
$.debounce = function(fn, time, ctx) {
var ret = 0;
if( typeof time !== 'number' ) {
ctx = time;
time = 50;
}
time = time || 50;
return function() {
var args = [].slice.apply(arguments);
// 注意是ctx的问题
// 错误写法:ctx = ctx || this,这样写ctx会被改变
var nctx = ctx || this;
clearTimeout(ret);
ret = setTimeout(function() {
fn.apply(nctx, args);
}, time);
}
}
/**
* throttle 操作
*/
$.throttle = function(fn, time, ctx) {
if( typeof time !== 'number' ) {
ctx = time;
time = 50;
}
time = time || 50;
var isLocked = false;
var isThrottleBeigin = false;
return function() {
var args = [].slice.apply(arguments);
var nctx = ctx || this;
if(!isThrottleBeigin){
setInterval(function(){isLocked = false;},time);
isThrottleBeigin = true;
}
if( !isLocked ) {
isLocked = true;
fn.apply(nctx, args);
}
}
}
//throttle 函数修改版
$.throttle = function(fn, time, ctx) {
if( typeof time !== 'number' ) {
ctx = time;
time = 50;
}
time = time || 50;
var isLocked = false;
return function() {
var args = [].slice.apply(arguments);
var nctx = ctx || this;
var timer;
if( !isLocked ) {
isLocked = true;
fn.apply(nctx, args);
timer = setTimeout(function(){isLocked = false;},time);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment