6

Edit: This is not the duplicate of how to pass params in setTimeout. Actually, I want to know how can write a function that would be called as a method on the predefined function just like the setTimeout API.

So, How can I write an implementation for a function 'callAfter' that enables any function to be called after some specified duration with certain parameters, with the following mentioned syntax:

Example: Lets say you have a function called 'sum' like so:

function sum(a, b) {
 console.log('Sum is: ', a + b);
}

Now you should be able to execute: sum.callAfter(5000, 8, 9);

which should invoke the function 'sum' after 5 seconds with parameters 8 and 9.

Swapnil Rai
  • 577
  • 6
  • 14

1 Answers1

11

Got it using Function prototyping:

Function.prototype.callAfter = function(){
    if(arguments.length > 1){
        var args = Array.prototype.slice.call(arguments);
        var time = args.splice(0,1);
        var func = this;
        setTimeout(function(){
            func.apply(null, args);
        }, time);
    }

}

Swapnil Rai
  • 577
  • 6
  • 14
  • Good answer, but as a side note, it's frowned upon to adjust the prototype of native JavaScript Objects. It works, but it can also cause issues when it comes to maintaining code and incorporating libraries. – zfrisch Jul 19 '17 at 21:44
  • @zfrisch True that. Can you show me a better solution? Actually, I am looking for the better approach. – Swapnil Rai Jul 20 '17 at 06:38