The setTimeout() method
The setTimeout()
method calls a function after a specified time provided in milliseconds. This method takes a function as a first argument and time in milliseconds as the second argument. You can write your logic inside the function body which will execute after the time you have specified.
For example: Show an alert box after 5 seconds.
setTimeout(()=> {
alert('Message after 5 seconds');
}, 5000);
To cancel the timer, you can store the timer first in a variable and call the clearTimeout()
function by passing the timer as argument.
var timer = setTimeout(()=> {
alert('Message after 5 seconds');
}, 5000);
clearTimeout(timer);
The setInterval() method
The setInterval()
method calls a function at specified interval of time provided in milliseconds. It takes function and time (in milliseconds) as its arguments.
For example: Print a random number every second.
setInterval(() => {
console.log(Math.random());
}, 1000);
To cancel the interval, you can store the interval first in a variable and call the clearInterval()
function by passing the interval as argument.
var interval = setInterval(() => {
console.log(Math.random());
}, 1000);
clearInterval(interval);
Create a running clock timer
To create a running clock, we need to take help of setInterval()
method and Date
object. We can get the current time by creating a new Date
object.
new Date().toLocaleTimeString(); // 4:50:16 PM
Once we create a Date
object, it will give us the information of current date and time, it will not change its value with the passing time. So we need to create a fresh new Date
object every time to get the latest date and time.
For this example, we will create a new Date
object every second and print that.
var date = setInterval(() => {
console.log(new Date().toLocaleTimeString());
}, 1000);
To show the running clock timer on a web page, you can create a div
element in HTML and set the it’s innerHTML
with the latest time every second.
<div id="time"> </div>
var date = setInterval(() => {
const element = document.getElementById('time');
element.innerHTML = new Date().toLocaleTimeString();
}, 1000);
You may also like
- Callback functions in JavaScript
- JavaScript Array forEach() method to loop through an Array
- 20 JavaScript Shorthand Coding Techniques that will save your time
Thanks for your time
For more web development blogs, please visit jscurious.com
Top comments (0)