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
1 Answer
Reset to default 11Got 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);
}
}
本文标签:
版权声明:本文标题:javascript - Implementation for a function 'callAfter' that enables any function to be called after some specifi 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745420047a2657859.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论