0

I have a simple addition function, it is working fine. But what I want is, the addition function want to execute after five seconds. How can I achieve this task with setTimeout.

Here is the addition function

function fun(a,b) {
  return (a+b)
}

fun(1,1)

Mr.
  • 9,429
  • 13
  • 58
  • 82
Vamsi
  • 151
  • 1
  • 4
  • 11

3 Answers3

2

Try this:

function fun(a, b) {
  return a + b
}

setTimeout(() => console.log(fun(1, 1)), 5000);

If you have a multiline function to execute:

setTimeout(() => {
  fun(1, 1);
  fun(3, 4)
}, 5000);

Since your requirement is a delay of five seconds and not five thousand miliseconds, you can improve the readability by specifying the number of seconds and then multiplying it by 1000:

setTimeout(() => {
  fun(1, 1);
}, 5 * 1000);

Don't forget that setTimeout is asynchronous, so any lines of code following fun(1, 1) will eventually be executed prior to fun

gekkedev
  • 562
  • 4
  • 18
1
setTimeout(() => {
  fun(1, 1)
}, 5000);
Chris Bendel
  • 86
  • 1
  • 4
0
function fun(a,b) {
  return (a+b)
}

setTimeout(fun(1,1), 5000);
Mosè Raguzzini
  • 15,399
  • 1
  • 31
  • 43
Vas Hanea
  • 120
  • 6