How To Pass This Function Into Settimeout With Parameters?
var test = function(a, b) { return a + b; }; setTimeout(test(2, 3), 3000); it shows some type error
Solution 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.
constpartial = (fn, ...firstArgs) => (...secondArgs) =>fn(...firstArgs, ...secondArgs);
var test = function(a, b) {
console.log(a + b);
return a + b;
};
setTimeout(partial(test, 2, 3), 3000);
Solution 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)
Post a Comment for "How To Pass This Function Into Settimeout With Parameters?"