-2

I have this code to test the setTimeout function. The console.log is logged immediately after executing the code. Any idea why this function isn't called after 5 second? What is wrong with this code?

function formatName(fname,lname){
  let fullName = fname+lname;
  console.log(fullName);
 }
setTimeout(formatName('Jon','Harris'),5000);

EDIT:
I didn't know about the way I need to call setTimeout.
shukla yogesh
  • 167
  • 1
  • 9

2 Answers2

2

First parameter of setTimeout() is the function, but in your code, you are executing the function. Make it as a function using arrow function.

function formatName(fname,lname){
  let fullName = fname+lname;
  console.log(fullName);
 }
setTimeout(() => formatName('Jon','Harris'),5000);
wangdev87
  • 8,611
  • 3
  • 8
  • 31
  • Like in any of those possible [dupe targets](https://stackoverflow.com/search?q=%5Bjs%5D+settimeout+immediately) – Andreas Dec 28 '20 at 15:44
2

You can pass parameters in the format:

setTimeout(formatName, 5000, fname, lname);

function formatName(fname, lname){
  let fullName = fname + ' ' + lname;
  console.log(fullName);
}
 
setTimeout(formatName, 5000, 'Jon', 'Harris');
s.kuznetsov
  • 14,870
  • 3
  • 10
  • 25