Search code examples
javascriptprototypesettimeoutcurrying

Currying with setTimeout - JS


I want to create a method for the Function prototype that will add a setTimeout automatically. I got it with this:

Function.prototype.defer = function (delay) {
  setTimeout(this, delay);
};
    
function f() {
  console.log("Hello!");
}
    
f.defer(1000);

And now I need to pass parameters to my function with currying like this:

function f(a, b) {
  console.log( a + b );
}

f.defer(1000)(4, 2);

And I achieved it with just currying but not with setTimeout:

Function.prototype.defer = function (delay) {
  return this
};

function f(a,b) {
  console.log(a + b);
}

f.defer(1000)(4, 2);

But when I try to add the setTimeout it loses its this or didn't recognize it as a function.


Solution

  • You need to return another function that will capture and pass arguments.

    Function.prototype.defer = function (delay) {
      return (...args) => setTimeout(this, delay, ...args)
    };
    
    function f(a,b) {
      console.log(a + b);
    }
    
    f.defer(1000)(4, 2);
    console.log('test')

    Or using bind

    Function.prototype.defer = function (delay) {
      return setTimeout.bind(null, this, delay)
    };
    
    function f(a,b) {
      console.log(a + b);
    }
    
    f.defer(2000)(4, 2);
    console.log('test')