How to pass this function into settimeout with parameters?

馋奶兔 提交于 2021-02-10 18:21:11

问题


var test = function(a, b) {   return a + b; }; 
setTimeout(test(2, 3), 3000);

it shows some type error


回答1:


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.

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

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



回答2:


This is the right way to call an external function inside setTimeout

var  test = function(a, b) { return a + b; };     
setTimeout(function() {test(2, 3)} , 3000)


来源:https://stackoverflow.com/questions/50540257/how-to-pass-this-function-into-settimeout-with-parameters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!