<HTML>
<body>
</body>
<script>
function f(a) {
console.log(a)
};
// f1000 passes calls to f at maximum once per 1000 ms
let f1000 = throttle(f, 1000);
function throttle(update, ms){
let isThrottled = false,
savedArgs,
savedThis; //context can be saved in let
function wrapper(){
if(isThrottled) { //if throttled is true, save latest call
savedArgs = arguments;
savedThis = this;
return;
}
update.apply(this,arguments);
//runs and book the next call
isThrottled = true;
setTimeout(function() {
//initiate the flag object and let wrapper runs again
isThrottled = false;
if(savedArgs) {
wrapper.apply(savedThis, savedArgs);
//calling the whole function wrapper makes the latest call's infos to be saved
savedArgs = savedThis = null;
}
}, ms);
}
return wrapper;
}
f1000(1); // shows 1
f1000(2); // (throttling, 1000ms not out yet)
f1000(3); // (throttling, 1000ms not out yet)
</script>
</HTML>
<body>
</body>
<script>
function f(a) {
console.log(a)
};
// f1000 passes calls to f at maximum once per 1000 ms
let f1000 = throttle(f, 1000);
function throttle(update, ms){
let isThrottled = false,
savedArgs,
savedThis; //context can be saved in let
function wrapper(){
if(isThrottled) { //if throttled is true, save latest call
savedArgs = arguments;
savedThis = this;
return;
}
update.apply(this,arguments);
//runs and book the next call
isThrottled = true;
setTimeout(function() {
//initiate the flag object and let wrapper runs again
isThrottled = false;
if(savedArgs) {
wrapper.apply(savedThis, savedArgs);
//calling the whole function wrapper makes the latest call's infos to be saved
savedArgs = savedThis = null;
}
}, ms);
}
return wrapper;
}
f1000(1); // shows 1
f1000(2); // (throttling, 1000ms not out yet)
f1000(3); // (throttling, 1000ms not out yet)
</script>
</HTML>
댓글
댓글 쓰기