9 Tweets Feb 14, 2023
What is the callback function? ๐Ÿ“ž๐Ÿ”™
A thread๐Ÿงต๐Ÿ‘‡๐Ÿป
In JavaScript, functions are typically executed sequentially. A function executes in the order in which you call it, not the order in which you define it.
Example๐Ÿ‘‡๐Ÿป
After seeing these examples, you might think, "Why complicate code when we can do this by simply changing the sequence to a function call?" Well, in this particular example, you can do that. There are so many other scenarios.
For example, if we 'setTimeout()' function on function pet1, setTimeout() is a function that executes a function after a given time. In the meantime, JavaScript executes other functions no matter what the sequence is.
Example๐Ÿ‘‡๐Ÿป
As you can see in the example we mentioned above, the dog() function does not wait for the cat() function to execute first.
If you want to execute one function before another, you can do so by using a callback function.
The function we pass as arguments to another function is called a callback function.
Example๐Ÿ‘‡๐Ÿป
No matter what the condition is, the callback function executes the primary function first.
In this example, pet1 receives pet2 as an argument. Pet1 starts executing after five seconds, and Pet2 waits for Pet1 to finish.
โšก Callback functions are useful when you have to wait for asynchronous functions that might take a while to complete.
That's all for today :))
If you find this helpful, then๐Ÿ‘‡๐Ÿป
โค๏ธLike
๐Ÿ”Retweet the first tweet.
โ˜‘๏ธFollow me @ishratUmar18 to read more about:
โ˜žHTML
โ˜ž CSS
โ˜žJavaScript
โ˜žFree Resource

Loading suggestions...