-
Notifications
You must be signed in to change notification settings - Fork 119
03: Updating Variables with setInterval()
As the Date object provides information about the current time we can use that to add a clock to our page. To do so we'll need to call our code every second to update the time.
Fortunately, Javascript has a method that can be used to call a function at a set time interval. As well as the document object, Javascript has a window object. The window object, like the document object, has a range of methods and properties. One method of the window object is setInterval(). The setInterval() methods takes two parameters, a function to call and then the time interval between function calls (a value in milliseconds). The function to be called can either be named or anonymous.
Calling an anonymous function would appear:
setInterval(function(){
// do something
}, 1000);
Notice that with the anonymous approach the first parameter is an entire function.
Calling a named function would appear as follows:
const updateTime = function(){
console.info('tick tock');
}
setInterval(updateTime, 1000);... and as an arrow function as:
const updateTime = () => {
console.info("tick tock");
};
setInterval(updateTime, 1000);Now we have a way to create the Date object every second ie:
const updateTime = () => {
console.info("tick tock");
const myDate = new Date();
};
setInterval(updateTime, 1000);Move the code creating and writing the time into the updateTime() as follows:
const updateTime = () => {
console.info("tick tock");
const myDate = new Date();
myNode.innerHTML = myDate.toLocaleTimeString("en-GB", { hour: "2-digit", minute: "2-digit", second: "2-digit" });
};
setInterval(updateTime, 1000);When tested you will notice a one second display. This is because the setInterval is not called until one second has elapsed. Fix that by initially calling the updateTime directly.
const updateTime = () => {
console.info("tick tock");
const myDate = new Date();
myNode.innerHTML = myDate.toLocaleTimeString("en-GB", { hour: "2-digit", minute: "2-digit", second: "2-digit" });
};
setInterval(updateTime, 1000);
updateTime();