Bummer! This is just a preview. You need to be signed in with a Basic account to view the entire video.
Using a One-Off Timer with setTimeout3:26 with Andrew Chalkley
In this video we'll explore one-off timers with the `setTimeout` function.
callback is a function and
delay is the number of milliseconds until the callback is invoked.
Canceling a Timeout
To cancel a timeout before the callback is executed assign the timeout to a variable and call the
const timeoutID = setTimeout(callback, delay); //Clears the timeout immediately clearTimeout(timeoutID);
Callbacks are really handy for timers.
Think if you wanted something to happen after a given period of time,
how would you do that?
after a given period of time.
The function is called setTimeout.
To show how a one off timer works we're going to build a simple surprise app.
After a random period of time, a surprise message will appear to the site's visitor.
Open the workspace with this video and you should see a surprise.js file.
Open the file, and you can see the first line of code
starts by selecting the section element with the ID of surprise.
The function showsSurprise, when invoked,
will update the text content of the surprise section.
It will update it to the surprise message.
Preview the application and then go to the developer console.
Let's call the function manually.
Instead of calling showSurprise ourselves,
we want it to be invoked after a random period of time.
To invoke or call a function after a period of time,
we can use the setTimeout function.
The setTimeout function requires a function which is a callback function and
a delay in milliseconds.
Let's use setTimeout in our code.
We'll pass in the showSurprise function as the first parameter.
Remember, you don't need a pair of parentheses,
because we're not invoking this show surprise function.
setTimeout is calling showSurprise after a given delay.
Let's add a delay for one second.
Save the file and preview the code in the browser.
As you can see, after a second the surprise message appears.
The surprise will only show after one second.
We want the surprise message to appear at a random time in a four second period.
Let's create a variable called randomTime.
Then, we'll use Math.random,
To generate a random value between one and zero.
Then we can multiply it by 4000, Which is four seconds.
Then we can update the setTimeout to use the random time.
Save the file and preview it a couple of times by refreshing.
As you can see, we have the surprise message appearing at different intervals.
Here's a challenge for you,
instead of passing in a reference to showSurprise into the setTimeout function,
modify the code to use an anonymous function to do the same thing.
In the next video, I'll show you how I did it.
You need to sign up for Treehouse in order to download course files.Sign up