A timer allows you to schedule the execution of a function at a specific time.
With timers, you can delay the execution of code so that it doesn't happen immediately when an event is triggered or when the page loads. For instance, you can use timers to rotate advertisement banners on your website at regular intervals or display a real-time clock. JavaScript offers two timer functions: setTimeout()
and setInterval()
.
Next, we'll demonstrate how to create timers to delay code execution and how to perform actions repeatedly using these functions in JavaScript.
The setTimeout()
function executes a specified function or piece of code once after a designated amount of time. Its syntax is setTimeout(function, milliseconds)
.
This function takes two parameters: a function (the function to execute) and an optional delay (the time to wait in milliseconds before executing the function; 1 second = 1000 milliseconds). Let's see an example:
<script>
function myFunction() {
alert('Hello World!');
}
</script>
<button onclick="setTimeout(myFunction, 2000)">Click Me</button>
The above example will show an alert message after a delay of 2 seconds when the button is clicked.
Note: If the delay parameter is omitted or not specified, the function provided to setTimeout()
is executed immediately, or as soon as possible.
Similarly, you can utilize the setInterval()
function to repeatedly execute a function or specified piece of code at fixed time intervals. Its basic syntax is setInterval(function, milliseconds)
.
This function also takes two parameters: a function (the function to execute) and an interval (the time in milliseconds to wait before executing the function; 1 second = 1000 milliseconds). Here's an example:
<script>
function showTime() {
var d = new Date();
document.getElementById("clock").innerHTML = d.toLocaleTimeString();
}
setInterval(showTime, 1000);
</script>
<p>The current time on your computer is: <span id="clock"></span></p>
The above example will repeatedly execute the showTime()
function every 1 second. This function retrieves the current time from your computer and displays it in the browser.
Both setTimeout()
and setInterval()
methods return a unique ID (a positive integer value, known as a timer identifier) which identifies the timer created by these methods.
This ID can be used to disable or clear the timer and stop the execution of code prematurely. Clearing a timer can be accomplished using two functions: clearTimeout()
and clearInterval()
.
The clearTimeout()
function takes a single parameter, which is the ID returned by setTimeout()
, to clear the timer associated with that ID. Here's an example:
<script>
var timeoutID;
function delayedAlert() {
timeoutID = setTimeout(showAlert, 2000);
}
function showAlert() {
alert('This is a JavaScript alert box.');
}
function clearAlert() {
clearTimeout(timeoutID);
}
</script>
<button onclick="delayedAlert();">Show Alert After Two Seconds</button>
<button onclick="clearAlert();">Cancel Alert Before It Display</button>
Similarly, the clearInterval()
method is employed to clear or disable a setInterval()
timer.
<script>
var intervalID;
function showTime() {
var d = new Date();
document.getElementById("clock").innerHTML = d.toLocaleTimeString();
}
function stopClock() {
clearInterval(intervalID);
}
var intervalID = setInterval(showTime, 1000);
</script>
<p>The current time on your computer is: <span id="clock"></span></p>
<button onclick="stopClock();">Stop Clock</button>
Note: Technically, you can use clearTimeout()
and clearInterval()
interchangeably. However, for clarity and code maintainability, it's recommended to use each method appropriately for their corresponding timers.