About Lesson
Time Functions:
1. Getting the Current Time:
JavaScript
const now = new Date();
console.log(`${now.getHours()}:${now.getMinutes()}:${now.getSeconds()}`);
// e.g., "14:30:15"
2. setTimeout:
Executes a function after a specified delay.
JavaScript
setTimeout(() => {
console.log("This message is displayed after 2 seconds");
}, 2000);
3. clearInterval:
The clearInterval()
function in JavaScript is used to stop the execution of a function that was previously established by the setInterval()
method.
JavaScript
let count = 0;
let intervalID = setInterval(function () {
count++;
document.getElementById("count").textContent = count;
}, 1000); // Increase count every second
function stopCounting() {
clearInterval(intervalID); // Stop the interval
alert("Counting stopped at: " + count);
}
4. setInterval:
Repeats execution of a function at a specified interval.
JavaScript
let count = 0;
const intervalId = setInterval(() => {
count++;
console.log(`Count: ${count}`);
if (count === 5) {
clearInterval(intervalId); // Stops the interval
}
}, 1000);