Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

311
Views
Callback function behaviour in JS

I came across callback functions in JS and found it to be really amazing. Though there is something about how callbacks behave that i am not able to understand. Example:

function add(num1, num2){
  return num1 + num2;
}

function displaySum(num1, num2, callback){
  let a = callback(num1, num2)
  console.log(a);
}

setTimeout(displaySum(3,5,add), 3000); // This displays the result instantly

And in a similar case

function displayText(text){
    console.log('HEY JS');
}
setTimeout(displayText, 3000) //This seems to work

I am not able to understand why is this happening?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

The issue is that you are directly calling the function inside the setTimeout. That function gets invoked and nothing is sent back.

setTimeout expects a function to be executed after the timer expires. You should only specify the referene to that function.

setTimeout(displaySum(3,5,add), 3000);

With the above statement you are instantly calling the displaySum function with 3 parameters. That is why you can see the result instantly. This function donot have a return value so there is no event that needs to be triggered after specified interval.

Replace that with

setTimeout(() => displaySum(3, 5, add), 3000);

Here the arraw function returns displaySum(3, 5, add), and this function will be called after specified interval.

function add(num1, num2) {
    return num1 + num2;
}

function displaySum(num1, num2, callback) {
    let a = callback(num1, num2)
    console.log(a);
}

setTimeout(() => displaySum(3, 5, add), 3000);

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!