如何将此函数带参数传递给settimeout? [英] How to pass this function into settimeout with parameters?
本文介绍了如何将此函数带参数传递给settimeout?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
var test = function(a, b) { return a + b; };
setTimeout(test(2, 3), 3000);
它显示一些类型错误
推荐答案
至少有两种方法可以实现这一点.第一个只是在作为回调传递给 setTimout
的新匿名函数内触发 test
函数.
There are at least two ways to achieve this.
The first one just fires the test
function inside of a new anonymous function passed as callback to the setTimout
.
第二个使用 .bind
来部分应用 test
函数.
The second one uses .bind
to partially apply the test
function.
var test = function(a, b) {
console.log(a + b);
return a + b;
};
setTimeout(() => {
test(2, 3);
}, 3000);
setTimeout(test.bind(null, 2, 3), 3000);
如果你不喜欢 .bind
的第一个(在这种情况下毫无意义的)参数 null
,那么你可以使用一些为你提供的库部分应用程序功能,或者您可以编写自己的函数来执行部分应用程序.
And if you don't like the first (in this case meaningless) argument null
of .bind
as I do, then you can use some library that provides you with partial application functionality or you can write your own function that performs partial application.
const partial = (fn, ...firstArgs) => (...secondArgs) =>
fn(...firstArgs, ...secondArgs);
var test = function(a, b) {
console.log(a + b);
return a + b;
};
setTimeout(partial(test, 2, 3), 3000);
这篇关于如何将此函数带参数传递给settimeout?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文