<html> <head> <metacharset="utf-8"> <title>JavaScript - Async - Level 1 - Callbacks</title> <metaname="viewport"content="width=device-width, initial-scale=1"> <metaname="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>