-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy path35 Call Back in JS.html
45 lines (39 loc) · 1.98 KB
/
35 Call Back in JS.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
<html lang="en">
<head>
<title>Call back in JS</title>
</head>
<body>
<!--
Note:{
callback functions are already studied in previous code 34 ,
here i'm making it simple to understand better }
-->
<script type="text/javascript">
//What are Callbacks in JavaScript?
//ANS: A callback is a function that is passed inside another function, and then called in that function to perform a task.
//Confusing? Let's break it down by practically implementing it.
console.log("Displayed first");
console.log("Displayed second");
setTimeout(() => {
console.log("Displayed third");
}, 3000);
console.log("Displayed fourth"); // will be displayed after second and before third as third is displayed 3 seconds later
//Explanation:
/*
-> The setTimeout is a JavaScript function that takes two parameters. The first parameter is another
function, and the second is the time after which that function should be executed in milliseconds.
Now you see the definition of callbacks coming into play.
-> You see that the last instruction is logged before the function in the setTimeout returns
its result. Say we used this method to fetch data from a database. While the user is waiting
for the database call to return results, the flow in execution will not be interrupted.
->This method was very efficient, but only to a certain point. Sometimes, developers have to
make multiple calls to different sources in their code. In order to make these calls,
callbacks are being nested until they become very hard to read or maintain.
This is referred to as Callback Hell
-> To fix this problem, promises were introduced.
-> Where callbacks really shine are in asynchronous functions, where one function has to wait
for another function (like waiting for a file to load).
*/
</script>
</body>
</html>