-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcallbackExaple.js
More file actions
65 lines (52 loc) · 1.53 KB
/
callbackExaple.js
File metadata and controls
65 lines (52 loc) · 1.53 KB
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
var Currentsalary = 52000;
async function getEmployee(empId, empname, callback) {
if (empId == 120 && empname == "raju") {
console.log(empId + " " + empname);
await callback(15000);
}
}
function salaryIncreaser(salary) {
Currentsalary += salary;
console.log(Currentsalary);
}
getEmployee(120, "raju", salaryIncreaser);
//Example 2
function delayedGreeting(callback) {
setTimeout(function () {
console.log("Hello, after 2 seconds!");
callback();
}, 2000);
}
function sayGoodbye() {
console.log("Goodbye!");
}
delayedGreeting(sayGoodbye);
//example 3
//Event Listener with Callback:
document.getElementById("myButton").addEventListener("click", function () {
//basically we have passed function to addEventListener that works like a callback
console.log("Button clicked!");
// Your callback logic here
});
// Here, the addEventListener method is used to attach a click
// event listener to an HTML button with the ID
// "myButton." The anonymous function serves as
// the callback that gets executed when the button is clicked.
// example 3
// Ajax Request with Callback:
function fetchData(url, callback) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
var data = JSON.parse(xhr.responseText);
callback(data);
}
};
xhr.open("GET", url, true);
xhr.send();
}
function handleData(data) {
console.log("Received data:", data);
// Your callback logic here
}
fetchData("https://api.example.com/data", handleData);