JavaScript Timing
JavaScript provides timing methods to execute code after a delay or at regular intervals. These methods enhance interactivity by controlling the execution of tasks over time.
Key Topics
setTimeout
The setTimeout
method executes a function after a specified delay (in milliseconds).
setTimeout(() => {
console.log("Executed after 2 seconds");
}, 2000);
Explanation: The setTimeout
method delays the execution of a function. In this example, the function logs a message to the console after 2 seconds.
setInterval
The setInterval
method repeatedly executes a function at specified intervals (in milliseconds).
let counter = 0;
const intervalId = setInterval(() => {
counter++;
console.log("Counter:", counter);
if (counter === 5) {
clearInterval(intervalId);
}
}, 1000);
Explanation: The setInterval
method repeatedly executes the function every second. The clearInterval
method stops the interval when the counter reaches 5.
clearTimeout and clearInterval
The clearTimeout
and clearInterval
methods cancel delayed or repeated executions set by setTimeout
and setInterval
.
const timeoutId = setTimeout(() => {
console.log("This will not execute");
}, 5000);
// Cancel the timeout
clearTimeout(timeoutId);
const intervalId = setInterval(() => {
console.log("Repeating task");
}, 1000);
// Cancel the interval after 3 seconds
setTimeout(() => {
clearInterval(intervalId);
}, 3000);
Explanation: The clearTimeout
method cancels a delayed execution, and the clearInterval
method stops repeated executions.
JavaScript Usage in DOM
Below is a DOM-based example demonstrating how to use timing methods to control dynamic updates on a webpage.
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Timing Example</title>
</head>
<body>
<button onclick="startCounter()">Start Counter</button>
<button onclick="stopCounter()">Stop Counter</button>
<p id="counter">0</p>
<script>
let counter = 0;
let intervalId;
function startCounter() {
intervalId = setInterval(() => {
counter++;
document.getElementById("counter").textContent = counter;
}, 1000);
}
function stopCounter() {
clearInterval(intervalId);
}
</script>
</body>
</html>
Key Takeaways
- setTimeout: Delays the execution of a function.
- setInterval: Repeats a function at specified intervals.
- Clear Methods: Use
clearTimeout
andclearInterval
to stop delayed or repeated executions. - Dynamic Updates: Timing methods enable precise control over the execution flow of scripts.