Adding a timer is easy with JavaScript. There’re 2 methods for adding a timer into our JavaScript app. One is the setTimeout
function. The other is the setInterval
function.
Thr setTimeout
function lets us run code after a given delay in milliseconds. It’s queue to be run after the given amount of delay time and then it’ll run the callback we pass in into the main thread.
For instance, we can use it as follows:
setTimeout(() => console.log('hi'), 1000);
In the code above, we passed in a callback function as the first argument of the time setTimeout
function and a 1000 ms delay as the second argument.
Then we should see 'hi'
logged in the console log output after 1 second.
We can also pass in arguments to the callback by passing in more arguments after the second argument. They can be accessed in the callback in the same order.
For instance, we can do that as follows:
setTimeout((greeting) => console.log(greeting), 1000, 'hi');
In the code above, we passed 'hi'
as the 3rd argument of setTimeout
, which will let us access the argument from the greeting
parameter.
Therefore, we’ll see 'hi'
logged in the console log output since greeting
is 'hi'
.
setTimeout
also takes a string instead of a callback as the first argument, where the string has the code that a callback normally has.
However, this prevents performance optimizations from being done and also presents security issues since attackers can potentially inject their own code as a string into the setTimeout
if we aren’t careful.
If we don’t need the timer any more, we can cancel the timer by calling the clearTimeout
function which takes the timer ID object that’s returned by setTimeout
.
For instance, we can do that as follows:
const timer = setTimeout((greeting) => console.log(greeting), 1000, 'hi');
clearTimeout(timer);
Since we called clearTimeout
immediately after calling setTimeout
, the callback won’t be called since we disposed of our timer with clearTimeout
.