Bummer! This is just a preview. You need to be signed in with a Basic account to view the entire video.
Using a Repeat Timer with setInterval2:27 with Andrew Chalkley
In this video we'll use a repeat timer in the form of the `setInterval` function to modify the display of a clock.
callback is a function and
delay is the number of milliseconds between each invocation.
Canceling a Timeout
To cancel a interval at any time assign the interval to a variable and call the
const intervalID = clearInterval(callback, delay); //Clears the interval immediately clearInterval(intervalID);
The setTimeout function only runs the callback one time.
There is another function will repeatedly call a call back after a delay
And that's the setInterval function.
Now that we're used to a one off timer,
we're going to use a repeat timer to build a clock like this.
Open the workspace accompanying this video.
First, let's select in this section element with the ID of clock on the page
and assigning it to the clockSection variable.
Then we have a getTime function that formats some time from today's date.
The get time function represents a string that represents the time.
Finally we have the tick clock function that displays the clock.
Click on the preview and you'll see the text clock goes here.
Open up the developer tools and you can call tickClock manually.
Instead of me calling the tickClock function over and over again myself I can
use this set interval function to execute the callback every second.
Remember one second is 1,000 milliseconds.
Save the clock and then preview.
We see clock goes here for one second, and then the clock ticks.
This is because the set interval function starts after the delay.
And is not invoked immediately.
To get around this, we can call the tickClock function immediately ourselves
when the page loads, and then let the setInterval do it every second afterwards.
Okay, I have another challenge for you.
Can you try and
use an anonymous function with these set interval in the clock application.
If you try and can't, can you explain why?
I'll share with you my thoughts and the solution next.
You need to sign up for Treehouse in order to download course files.Sign up