functions-throttle1

by shan10213223

JavaScript

var _ = {};
// _.throttle(function, wait)
// Returns a new, throttled version of the passed function that,
// when invoked repeatedly, will only call the original function
// at most once per every wait milliseconds, and otherwise will
// just return the last computed result. Useful for rate-limiting
// events that occur faster than you can keep up with.
_.throttle = function (func, wait) {
  let lastCall = 0;
  //let lastResult;
  //let lastResult = func(...args);;
  const newFunc = function (...args) {
    const now = (new Date()).getTime();
    if (now - lastCall < wait) {
      return;
      //return lastResult;
    }
    //lastCall = now;
    let output = func(...args);
    return func(...args);
  }
    
  };
  
  newFunc.lastResult = func(input);
  newFunc.lastCalled = (new Date()).getTime();
  return newFunc;
};

/*var intervalID = window.setInterval(myCallback, 5000);
function myCallback() {
  // Your code here
  console.log('hello');
}
console.log(intervalID);
clearInterval(intervalID);*/

function echo () {
  return 'hello';
}

let test2 = _.throttle(echo, 500);
console.log(test2, test2.lastCalled);




function mythrottle (wait) {
  let lastCall = 0;
  let lastResult;
  let now = (new Date()).getTime();
  let delta = now - lastCall;
  
  // if called the first time, return modefied function
  if (lastCall === 0) {
    lastResult = echo();
    lastCall = now;
    return echo;
  } else if (delta < wait) {
    // if less than wait
    return lastResult;
  } else {
    echo();
  }
}

//let test1 = mythrottle(5000);
//console.log(test1);
//console.log(test1);
//console.log(test1);