-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path15-Timing-&-Interval-Functions.html
More file actions
92 lines (74 loc) · 2.33 KB
/
15-Timing-&-Interval-Functions.html
File metadata and controls
92 lines (74 loc) · 2.33 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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>15-Timing-&-Interval-Functions</title>
</head>
<body>
<script>
/* ===============================
setTimeout() – BASIC EXAMPLE
Runs code once after a delay
=============================== */
setTimeout(() => {
console.log("Hello after 2 seconds");
}, 2000); // runs after 2 seconds
/* ===============================
setTimeout() with clearTimeout()
Canceling a timeout
=============================== */
const timeout = setTimeout(() => {
console.log("This will not run");
}, 3000);
console.log(timeout); // timeout ID
clearTimeout(timeout); // cancels the timeout
/* ===============================
Another clearTimeout example
=============================== */
const timeout2 = setTimeout(() => {
console.log("This will not run");
}, 3000);
console.log(timeout2); // timeout ID
clearTimeout(timeout2); // timeout cancelled
/* ===============================
setInterval() – BASIC EXAMPLE
Runs code repeatedly
=============================== */
const intervalID = setInterval(() => {
console.log("Running every second");
}, 1000);
console.log(intervalID); // interval ID
clearInterval(intervalID); // interval stopped immediately
/* ===============================
PRACTICAL EXAMPLE
Countdown Timer
=============================== */
let count = 10;
const timer = setInterval(() => {
console.log(count);
count--;
// stop timer when count is finished
if (count < 0) {
clearInterval(timer);
console.log("Time's up!");
}
}, 1000);
/* ===============================
PRACTICAL EXAMPLE
Loading Animation
=============================== */
let dots = 0;
const loader = setInterval(() => {
dots++;
console.log("Loading" + ".".repeat(dots));
// reset dots after 3
if (dots === 3) {
dots = 0;
}
}, 500);
</script>
</body>
</html>
```