JavaScript - Async - Generation 1 - Callbacks

From
https://www.joshwcomeau.com/javascript/promises/

Sample code

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
<html>
<head>
<meta charset="utf-8">
<title>JavaScript - Async - Level 1 - Callbacks</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="used by atom.xls">
</head>
<body>
<h1>JavaScript - Async - Level 1 - Callbacks</h1>

Callbacks were the first generation of multitasking within the language. The example given is setting up a timer and keeping the concurrency running.

Here is a sample of a countdown.

<script>
// Run JavaScript after the DOM is fully loaded
document.addEventListener('DOMContentLoaded', function () {
console.log('DOM fully loaded and parsed.');
// Your script logic here

console.log('Start');
console.log("3…");

setTimeout(() => {
console.log("2…");
setTimeout(() => {
console.log("1…");
setTimeout(() => {
console.log("Happy New Year!!");
}, 1000);
console.log("1…After setTimeout");
}, 1000);
console.log("2…After setTimeout");
}, 1000);
console.log("3…After setTimeout");

// end of event listener
});
</script>

With callback you find yourself embedding code, deeper and deeper. It get's confusing as is referred to as Callback Hell.

Since JavaScript is not a truly multitasking (or multithreaded language) the rule of setTimeout is 1000 milliseconds at a minumum.
</body>

</html>