Search code examples
javascripttimeoutsettimeout

setTimeout executes immediately instead of time passed in the function call


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.


Solution

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