Robert Hovhannisyan
Robert Hovhannisyan

Reputation: 3341

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.

Upvotes: 1

Views: 197

Answers (2)

Pointy
Pointy

Reputation: 413916

You can do it with a modification to your .defer() function:

    Function.prototype.defer = function (delay, ... args) {
      setTimeout(this.bind(undefined, ... args), delay);
    };
        
    function f(a, b) {
      console.log("a + b is " + (a + b));
    }
    
    f.defer(2000, 4, 5);
    

Upvotes: 2

Yury Tarabanko
Yury Tarabanko

Reputation: 45106

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')

Upvotes: 2

Related Questions