Event Handling: How to Work with Timers in JavaScript


show more Want to trigger your JavaScript code to run after a certain amount of time? Learn how to use timer methods such as setInterval and setTimeout (and their companions clearInterval and clearTimeout) to perform actions after a certain delay and repeat an action after a delay. show less
please wait ...

Working with timers

It's very common to want to trigger some JavaScript to run but to run later, to call a function after 60 seconds, or to call a function every 5 seconds, and we use timers for these. Slideshows would use timers, clocks would use timers, and there are lots more uses for them. While timers aren't officially events in JavaScript, they can feel a little bit like it, so we will talk about them here. Really, there are only two methods that we are interested in. I'm looking at a little bit of code here, but there is nothing to do with timers just yet.

I have a function defined called simpleMessage. I'm going to add just a call to setTimeout. We can just call setTimeout directly the same way we could call alert or console.log. It's always available. All I need to give it is two things: the name of the function I want to call--in this case simpleMessage, comma--and the interval. Now, setTimeout is used in milliseconds, so if I wanted to say pop up five seconds later, I'll put in...

Working with timers
Video duration: 6m 17s 5h 31m Beginner

Viewers:

Want to trigger your JavaScript code to run after a certain amount of time? Learn how to use timer methods such as setInterval and setTimeout (and their companions clearInterval and clearTimeout) to perform actions after a certain delay and repeat an action after a delay.

Subjects:
Developer Web
Software:
JavaScript
Author:
please wait ...