0

I'm having an hard time really understanding the Callback principle in JavaScript. Maybe it is because of translation from English to Dutch, but it doesn't grab my comprehension.

Can anyone explain what a CallBack exactly is, and how it works (and how it not works)?

Wolk9
  • 69
  • 8
  • 1
    callback is just a function that is passed to another function as an argument. Read: [MDN - Callback function](https://developer.mozilla.org/en-US/docs/Glossary/Callback_function) – Yousaf Jun 24 '21 at 06:31
  • Well that makes sense in itself, though it is not self explaining. Can you give an example? – Wolk9 Jun 24 '21 at 06:33
  • 1
    @Wolk9 Say you have a function that writes to a file. This can take a bit of time. When it's done, you want to display a notice to the user. So the write function takes a callback as an argument and runs it when it's done writing, and when you call the write-function, you can give it a function as that callback which does whatever you want to happen at that time, like showing a message. – Amunium Jun 24 '21 at 06:35
  • Partly. Thanks @jonrsharpe – Wolk9 Jun 24 '21 at 07:07

2 Answers2

1

callback is a function that is passed as a parameter to another function. Most common example is setTimout. It takes a function and time as parameter.

setTimeout(function(){//do something here},2000);

Here the function defined in the setTimeout is the callback function.

Amir Ahmed
  • 119
  • 6
1

Don't worry, you're like most developers when they learn about callbacks. It's an idea that takes a little time to get used to.

There are some good examples of why we use callbacks in some situations.

For example, if we create a button, we'd like to know then it's clicked. We do this by assigning a callback function, say buttonClicked(). In that function you can do something cool like popping up a message "Hey thanks for clicking!"

Likewise, we use callbacks for timers. If we want a timer to run, say every 5 seconds, we assign a callback like timerFired()

function buttonClicked() {
    alert("Hey thanks for clicking!")
}
<html>
    <body>
        <h3>Button Example</h3>
        <button type="button" onclick="buttonClicked()">Click Me!</button>
    </body>
</html>

function timerFired() {
    console.log("Timer fired");
}

setInterval(timerFired, 5000);
Terry Lennox
  • 29,471
  • 5
  • 28
  • 40