Skip to main content

Debounce and throttle script

 

function debounce(fn, delay) {
  var timer = null;
  return function () {
    var context = this, args = arguments;
    clearTimeout(timer);
    timer = setTimeout(function () {
      fn.apply(context, args);
    }, delay);
  };
}
 
$('input.username').keypress(debounce(function (event) {
  // do the Ajax request
}, 250)); 




function throttle(fn, threshhold, scope) {
  threshhold || (threshhold = 250);
  var last,
      deferTimer;
  return function () {
    var context = scope || this;

    var now = +new Date,
        args = arguments;
    if (last && now < last + threshhold) {
      // hold on to it
      clearTimeout(deferTimer);
      deferTimer = setTimeout(function () {
        last = now;
        fn.apply(context, args);
      }, threshhold);
    } else {
      last = now;
      fn.apply(context, args);
    }
  };
}
 
 
$('body').on('mousemove', throttle(function (event) {
  console.log('tick');
}, 1000)); 

Comments

Popular posts from this blog

Recursive array calls one after another through promise

 data = [1,2,3,4] rules = [                     function(d){ return d.map(x => x * 2); },                     function(d){ return d.map(x => x * 2); }                ] recursive(0,rules,data); function somelongrunningprocess(rule, data){     var d = $.Deferred();     setTimeout(function(){ var result = rule.call(undefined,data); d.resolve(result); },1000);     return d; } function recursive(index, rules, data) {             if(index < rules.length) {                 $.when(somelongrunningprocess(rules[index],data)).then(function(response){                     console.log("after_rule",respon...

Javascript Generator as promise

     function* makeIterator(data) {       for(i in data){                 yield data[i];         }     }         function runPull() {         var obj = it.next();         var val;         console.log("RunPull Clicked",obj);         if(!obj.done) {             val = obj.value;             val.click();             setTimeout(function(){                 runPull();             },200);         }     }     ru...