New Feature: Playlist Center! Pick a topic and let our playlists guide the way.

Easy-to-follow video tutorials help you learn software, creative, and business skills.Become a member

Working with timers

From: JavaScript Essential Training

Video: 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.

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 5000.

Finish that statement. We can ignore anything that's below it. Right now, it's not being used yet. I am going to save that, and I'm going to refresh the page that I am on that's actually using this. Open that up, and then hopefully in about 5 seconds, we get the alert box. Yes, I agree, not very exciting, but it proves the point. Now, when I use setTimeout, it just happens once. It hits that line of code and says, "I am going to do this once and that's it." We also have a different one called setInterval.

setInterval takes exactly the same format, but it repeats it. In this case, setInterval will call the function called changeImage every five seconds. Now, what do I have going on here? Well, just to break it down, what I am doing is on line 10 I'm grabbing hold of an element of the page called mainImage, and if I look at the HTML here, all I have is that mainImage isn't a regular image tag in the main section of my document.

So I am grabbing hold of that, so I can change the source of it. On line 12 and 13 I am creating an array, using the shorthand format within the square brackets, and all I'm putting in it is six paths to images, and these are just some images I have locally in the _images folder that I have here. I've gone through and manually entered these. Now what I am going to do is rotate around them.

So I am creating my own little index here, which I will set at position 0, and then in my function called changeImage I'm going to reach into that image and set its source attribute to whatever the current contents of the array are at the current index. So the first time we call it it will say, "Well, my index is set to 0. I will grab the image that's called overlook. jpg, and just add that entry to the image tag." Then we add one to the imageIndex.

We check to see if the index is larger than the length of the array; it isn't. So I am done with the function. But setInterval is still ticking, and in five more seconds it's going to call changeImage again. We then grab the second element, we change the attribute, we increment the index, and we just keep going. So if I save this, go back over to my page, and hopefully, after about five seconds we change to one image, we wait a few more seconds, it will change to the next one, and as we watch, it would keep going and just start to loop around.

A very simple use, and all we're really doing here is the setInterval. But both setTimeout which is the single one and setInterval which is the repeating one have their mirror images, the ability to both clearTimeout and clearInterval. So just because we start something repeating, doesn't mean we always want to go on that way. The question is, how do we do it? Well, here's the interesting thing. When we call setInterval--I am just going to bring it up a little bit so I can see more to it-- this function actually returns a value, and I'm going to store it.

I didn't care before, but now I do. I'm going to create a new variable called intervalHandle. That's as good a name as any. It's just going to be a variable that connects me to a little bit of memory that says 'I understand what this interval is doing.' What I am then going to do is say, when somebody clicks on the image--so I'll use the myImage.onclick event = function(), just a small anonymous function-- I'm going to call, instead of setInterval, I am going to call clearInterval, passing in that interval handle, the variable that was returned from calling setInterval.

Now, you might think, "Well what does that do?" It allows me to create this ticking clock, this setInterval, and if I want to pass that value right into clearInterval then it knows which one to clear. The idea of this is I could have multiple intervals kicking off in my JavaScript. I don't want to clear all of them or none of them; I need to know one at a time. So I'll save that, jump back over, and open my page again, and we should have the ticking clock going on. The setInterval should be refreshing this image every five seconds.

But if I click on it, single-click, I'm not asking for any feedback, but that setInterval should now be cleared. And as you notice, the picture is not ticking over anymore. That is simply timers in JavaScript. Working with timers in JavaScript really boils down to those four methods: setTimeout to perform a single action after a delay, setInterval to repeat it after that delay and just keep on repeating, and their evil twins clearTimeout and clearInterval.

Show transcript

This video is part of

Image for JavaScript Essential Training
JavaScript Essential Training

56 video lessons · 99464 viewers

Simon Allardice
Author

 
Expand all | Collapse all
  1. 3m 28s
    1. Welcome
      1m 1s
    2. What you should know
      1m 44s
    3. Using the exercise files
      43s
  2. 15m 41s
    1. Introduction to JavaScript
      8m 6s
    2. Creating your first JavaScript
      2m 13s
    3. Getting to know the tools and applications
      5m 22s
  3. 56m 8s
    1. Understanding the structure of JavaScript code
      7m 9s
    2. Where to write your JavaScript
      3m 56s
    3. Creating variables
      6m 21s
    4. Working with conditional code
      5m 44s
    5. Working with operators
      13m 28s
    6. Sending messages to the console
      2m 59s
    7. Working with loops
      8m 1s
    8. Creating functions
      8m 30s
  4. 36m 13s
    1. Working with arrays
      7m 57s
    2. Working with numbers
      6m 13s
    3. Working with strings
      8m 27s
    4. Working with dates
      5m 38s
    5. Working with objects
      7m 58s
  5. 9m 6s
    1. What is the DOM?
      5m 49s
    2. Working with nodes and elements
      3m 17s
  6. 25m 17s
    1. Accessing DOM elements
      11m 3s
    2. Changing DOM elements
      5m 42s
    3. Creating DOM elements
      8m 32s
  7. 24m 45s
    1. Introduction to JavaScript event handling
      8m 16s
    2. Working with onClick and onLoad events
      7m 36s
    3. Working with onBlur and onFocus events
      2m 36s
    4. Working with timers
      6m 17s
  8. 21m 41s
    1. Common JavaScript errors
      7m 14s
    2. Using Firebug
      4m 7s
    3. Going through a debugging session
      10m 20s
  9. 10m 13s
    1. Accessing form elements
      4m 20s
    2. Preventing a form from being submitted
      2m 36s
    3. Hiding and showing form sections
      3m 17s
  10. 9m 49s
    1. CSS and JavaScript
      3m 46s
    2. Removing and applying CSS classes
      2m 16s
    3. Changing inline styles
      3m 47s
  11. 19m 44s
    1. Understanding JavaScript style
      7m 39s
    2. Minifying your code
      4m 28s
    3. Using JavaScript code checkers
      7m 37s
  12. 22m 24s
    1. Introduction to JavaScript libraries
      3m 17s
    2. Linking to multiple JavaScript files
      2m 11s
    3. Introduction to jQuery
      12m 7s
    4. Using a content distribution network to deliver JavaScript files
      4m 49s
  13. 17m 35s
    1. JavaScript in HTML5
      9m 37s
    2. Using Modernizr
      3m 2s
    3. Using Strict Mode
      4m 56s
  14. 33m 3s
    1. Knowing the JavaScript to avoid
      6m 35s
    2. Introduction to regular expressions
      6m 56s
    3. Working with AJAX
      10m 44s
    4. Working with objects and prototypes
      8m 48s
  15. 21m 10s
    1. Example: Countdown
      8m 3s
    2. Example: Resize
      5m 47s
    3. Example: Accordion
      7m 20s
  16. 4m 58s
    1. Where to go from here
      4m 0s
    2. Goodbye
      58s

Start learning today

Get unlimited access to all courses for just $25/month.

Become a member
Sometimes @lynda teaches me how to use a program and sometimes Lynda.com changes my life forever. @JosefShutter
@lynda lynda.com is an absolute life saver when it comes to learning todays software. Definitely recommend it! #higherlearning @Michael_Caraway
@lynda The best thing online! Your database of courses is great! To the mark and very helpful. Thanks! @ru22more
Got to create something yesterday I never thought I could do. #thanks @lynda @Ngventurella
I really do love @lynda as a learning platform. Never stop learning and developing, it’s probably our greatest gift as a species! @soundslikedavid
@lynda just subscribed to lynda.com all I can say its brilliant join now trust me @ButchSamurai
@lynda is an awesome resource. The membership is priceless if you take advantage of it. @diabetic_techie
One of the best decision I made this year. Buy a 1yr subscription to @lynda @cybercaptive
guys lynda.com (@lynda) is the best. So far I’ve learned Java, principles of OO programming, and now learning about MS project @lucasmitchell
Signed back up to @lynda dot com. I’ve missed it!! Proper geeking out right now! #timetolearn #geek @JayGodbold

Are you sure you want to delete this note?

No

Thanks for signing up.

We’ll send you a confirmation email shortly.


Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

Keep up with news, tips, and latest courses with emails from lynda.com.

Sign up and receive emails about lynda.com and our online training library:

Here’s our privacy policy with more details about how we handle your information.

   
submit Lightbox submit clicked
Terms and conditions of use

We've updated our terms and conditions (now called terms of service).Go
Review and accept our updated terms of service.