Skip to content

Commit fc3db90

Browse files
committed
learn about setting timers and intervals
1 parent 0ac23f4 commit fc3db90

File tree

4 files changed

+66
-3
lines changed

4 files changed

+66
-3
lines changed

Advanced-DOM-APIs/README.md

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
| [Handling Scrolling](#handling-scrolling) |
99
| [Working with `<template>` tag](#working-with-template-tag) |
1010
| [Loading Script Dynamically](#loading-script-dynamically) |
11+
| [Setting Timers and Intervals](#setting-timers-and-intervals) |
1112

1213
Below topics will be covered and for its practical application, [Planner Project](project_planner/) will be used as reference where concept of classes and functions are demonstrated:
1314

@@ -229,3 +230,41 @@ In this example, we add an event listener for the `load` event on the `script` e
229230
> **Note**
230231
>
231232
> Adding scripts dynamically can be a powerful feature, but it's important to use it carefully. If you're dynamically rendering user-created scripts, you need to be especially cautious, as this could make your website vulnerable to attacks like cross-site scripting. This type of attack involves injecting malicious code into your website's code, and we'll be discussing it in more detail in the security section later in the course. To avoid these kinds of attacks, it's crucial that you don't dynamically add a script based on user-entered content, or if you must do so, be sure to validate and sanitize the content thoroughly before executing it.
233+
234+
## Setting Timers and Intervals
235+
236+
You can use timers and intervals to execute code after a set amount of time has elapsed. Here's how you can set a timer and an interval using the DOM:
237+
238+
### Setting a timer using [`setTimeout`](https://developer.mozilla.org/en-US/docs/Web/API/setTimeout)
239+
240+
```javascript
241+
// Set a timer to execute some code after 3 seconds
242+
const timer = setTimeout(() => {
243+
// Code to be executed after 3 seconds
244+
}, 3000);
245+
```
246+
247+
In this example, `setTimeout` is used to set a timer that will execute the function after 3 seconds (3000 milliseconds) have elapsed. The function can contain any code you want to execute after the specified time.
248+
249+
### Setting an interval using [`setInterval`](https://developer.mozilla.org/en-US/docs/Web/API/setInterval)
250+
251+
```javascript
252+
// Set an interval to execute some code every 2 seconds
253+
const interval = setInterval(() => {
254+
// Code to be executed every 2 seconds
255+
}, 2000);
256+
```
257+
258+
In this example, `setInterval` is used to set an interval that will execute the function every 2 seconds (2000 milliseconds). Again, the function can contain any code you want to execute at regular intervals.
259+
260+
To clear a timer or interval, you can use the `clearTimeout` or `clearInterval` methods respectively. For example:
261+
262+
```javascript
263+
// Clear the timer
264+
clearTimeout(timer);
265+
266+
// Clear the interval
267+
clearInterval(interval);
268+
```
269+
270+
In this example, `clearTimeout` is used to cancel the timer and prevent the code from executing after the specified time. `clearInterval` works similarly for intervals.
Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1,14 @@
1-
console.log("Starting some analysis...")
1+
// console.log("Starting some analysis...");
2+
3+
// Demonstration of setInterval()
4+
5+
const intervalId = setInterval(() => {
6+
console.log("Starting some analysis...")
7+
}, 2000);
8+
9+
document.getElementById('stop-analytics').addEventListener(
10+
'click', () => {
11+
clearInterval(intervalId);
12+
// clearTimeout() will also work
13+
}
14+
)

Advanced-DOM-APIs/project_planner/assets/scripts/app.js

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -158,7 +158,15 @@ class App {
158158
const finishedProjectsList = new ProjectList('finished');
159159
activeProjectsList.setSwitchHandlerFunction(finishedProjectsList.addProject.bind(finishedProjectsList));
160160
finishedProjectsList.setSwitchHandlerFunction(activeProjectsList.addProject.bind(activeProjectsList));
161-
document.getElementById('start-analytics').addEventListener('click', this.startAnalytics);
161+
162+
/*
163+
This is an example of how JavaScript can execute code asynchronously via setTimeout() and setInterval(), a topic we haven't covered yet. When you set a timer in JavaScript, it won't pause the execution of your entire script. Instead, the browser registers the timer in the background and manages it, so your script can continue to run normally without interruption. When the timer expires, the browser will execute the registered function. It's important to understand that this process doesn't pause script execution, and the browser takes care of managing the timer in the background. This ensures that your script can continue to run without any pauses or disruptions.
164+
*/
165+
// document.getElementById('start-analytics').addEventListener('click', this.startAnalytics);
166+
const timerId = setTimeout(this.startAnalytics, 3000);
167+
168+
// If you click on `Stop Analytics` button before 3 seconds, the action will not be happened
169+
document.getElementById('stop-analytics').addEventListener('click', () => {clearTimeout(timerId);})
162170
}
163171

164172
// This is just a random function to demonstrate about adding a JS dynamically on some event

Advanced-DOM-APIs/project_planner/index.html

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -65,8 +65,11 @@ <h2>Book Hotel</h2>
6565
</ul>
6666
</section>
6767
<footer>
68-
<button id="start-analytics">
68+
<!-- <button id="start-analytics">
6969
Start Analytics!
70+
</button> -->
71+
<button id="stop-analytics">
72+
Stop Analytics!
7073
</button>
7174
</footer>
7275
</body>

0 commit comments

Comments
 (0)