Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementation for a function 'callAfter' that enables any function to be called after some specified duration

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.

like image 576
Swapnil Rai Avatar asked Jul 19 '17 20:07

Swapnil Rai


1 Answers

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);
    }

}

like image 84
Swapnil Rai Avatar answered Sep 28 '22 01:09

Swapnil Rai