admin管理员组

文章数量:1428562

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.

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.

Share Improve this question edited Jul 20, 2017 at 9:10 Swapnil Rai asked Jul 19, 2017 at 20:42 Swapnil RaiSwapnil Rai 5776 silver badges14 bronze badges 5
  • Use timeout. w3schools./js/js_timing.asp – Etherealm Commented Jul 19, 2017 at 20:44
  • Possible duplicate of How can I pass a parameter to a setTimeout() callback? – Etherealm Commented Jul 19, 2017 at 20:46
  • 1 Sounds like an interview/homework question. What have you tried so far? – lxe Commented Jul 19, 2017 at 20:46
  • 1 @lxe Finally, Got a solution using Function prototyping. – Swapnil Rai Commented Jul 19, 2017 at 21:28
  • Overriding prototype of Function is neat, but is considered by some to be an anti-pattern. – lxe Commented Jul 19, 2017 at 21:51
Add a ment  | 

1 Answer 1

Reset to default 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);
    }

}

本文标签: