File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ # [ Episode 14] ( https://www.youtube.com/watch?v=lW_erSjyMeM&list=PLlasXeu85E9cQ32gLCvAvr9vNaUccPVNP&index=16 ) : Callback Functions in JS ft. Event Listeners 🔥
2+
3+
4+ ### Callback Function in JS
5+
6+ ```
7+ setTimeout(function (){
8+ console.log("timer");
9+ },5000);
10+
11+ function x(y){
12+ console.log("x");
13+
14+ }
15+ x(function y(){
16+ console.log("y");
17+ });
18+ ```
19+
20+ Output:
21+ > timer
22+ > x
23+ > y
24+
25+ ** Explanation**
26+
27+ Settimeout is an async function; it takes a function and executes after x miliseconds.
28+
29+ The JS thread continues to execute other code and the call stack is filled and emptied.
30+
31+ Once the call stack is empty, it checks if the async queue is filled; then it executes those functions in the queue.
32+
33+ Thus output is x, y and then timer.
34+
35+ JS is single threaded synchronous language.
36+
37+ ### Important Interview Question
38+
39+ ```
40+ function attachEventListeners(){
41+ let count=0;
42+ document.getElementById("clickMe").addEventListener("click", console.log("Button", ++count));
43+ }
44+
45+ attachEventListeners();
46+ ```
47+
48+ ### removeEventListeners
49+
50+ Event Listeners are memory-heavy. Thus we must use removeEventListeners.
51+
52+
You can’t perform that action at this time.
0 commit comments