Bummer! This is just a preview. You need to be signed in with a Basic account to view the entire video.
Start a free Basic trial
to watch this video
In this video we'll use a repeat timer in the form of the `setInterval` function to modify the display of a clock.
Syntax
setInterval(callback, delay);
Where 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 clearInterval
function.
const intervalID = clearInterval(callback, delay);
//Clears the interval immediately
clearInterval(intervalID);
-
0:00
The setTimeout function only runs the callback one time.
-
0:05
There is another function will repeatedly call a call back after a delay
-
0:09
continually.
-
0:10
And that's the setInterval function.
-
0:13
Now that we're used to a one off timer,
-
0:15
we're going to use a repeat timer to build a clock like this.
-
0:20
Open the workspace accompanying this video.
-
0:23
In the clock.js file there's some JavaScript code already.
-
0:27
First, let's select in this section element with the ID of clock on the page
-
0:32
and assigning it to the clockSection variable.
-
0:35
Then we have a getTime function that formats some time from today's date.
-
0:41
The get time function represents a string that represents the time.
-
0:46
Finally we have the tick clock function that displays the clock.
-
0:51
Click on the preview and you'll see the text clock goes here.
-
0:58
Open up the developer tools and you can call tickClock manually.
-
1:11
Instead of me calling the tickClock function over and over again myself I can
-
1:16
use this set interval function to execute the callback every second.
-
1:35
Remember one second is 1,000 milliseconds.
-
1:40
Save the clock and then preview.
-
1:44
We see clock goes here for one second, and then the clock ticks.
-
1:50
This is because the set interval function starts after the delay.
-
1:57
And is not invoked immediately.
-
2:00
To get around this, we can call the tickClock function immediately ourselves
-
2:04
when the page loads, and then let the setInterval do it every second afterwards.
-
2:11
Okay, I have another challenge for you.
-
2:14
Can you try and
-
2:15
use an anonymous function with these set interval in the clock application.
-
2:20
If you try and can't, can you explain why?
-
2:24
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