Last active
February 19, 2016 04:16
-
-
Save lushijie/20a7c9379a1baafb0b8f to your computer and use it in GitHub Desktop.
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
$.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