functions-throttle3

by shan10213223

JavaScript

// _.throttle(function, wait)
var _ = {};
// 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 firstCall = true;
  let lastResult;
  //let lastResult = func(...argss);;
  return function (input) {
    const now = (new Date()).getTime();
    //if (lastResult === undefined) {
    //  lastResult = func(...args);
    //}
    if (firstCall === true) {
      console.log('first time');
      //console.log(func(input));
      lastResult = func(input);
      //console.log(lastResult);
      firstCall = false;
      //lasResult = func.apply(this, args);
      //firstCall = false;
    } else if (now - lastCall < wait) {
      console.log('after first time');
      return lastResult;
    }
    //if (now - lastCall < wait) {
    //  //return 300;
    //  return lastResult;
    //}
    lastCall = now;
    //console.log(func.apply(this, input));
    //lasResult = func.apply(this, args);
    return func(input);
  }
};

function myplus (n) {
  return n + 1;
}

let test1 = _.throttle(myplus, 5000);
console.log(test1(1));
console.log(test1(2));
console.log(test1(3));
console.log(setTimeout(test1, 5000, 10));