• Skip to main content
  • Skip to primary sidebar
  • Skip to footer

Matt Doyle | Elated Communications

Web and WordPress Development

  • About Me
  • Blog
    • Design & Multimedia
      • Photoshop
      • Paint Shop Pro
      • Video & Audio
    • Online Marketing
      • E-Commerce
      • Social Media
    • Running a Website
      • WordPress
      • Apache
      • UNIX and Linux
      • Using FTP
    • Web Development
      • HTML
      • CSS
      • JavaScript
      • PHP
      • Perl and CGI Scripting
  • Portfolio
  • Contact Me
  • Hire Me
Home / Blog / Web Development / JavaScript / JavaScript Timers with setTimeout and setInterval

JavaScript Timers with setTimeout and setInterval

15 January 2007 / 24 Comments

JavaScript features a handy couple of methods of the window object: setTimeout() and setInterval(). These let you run a piece of JavaScript code at some point in the future. In this tutorial we’ll explain how these two methods work, and give some practical examples.

setTimeout()

window.setTimeout() allows you to specify that a piece of JavaScript code (called an expression) will be run a specified number of milliseconds from when the setTimeout() method was called. The general syntax of the method is:


setTimeout ( expression, timeout );

where expression is the JavaScript code to run after timeout milliseconds have elapsed.

setTimeout() also returns a numeric timeout ID that can be used to track the timeout. This is most commonly used with the clearTimeout() method (see below).

Here’s a simple example:


<input type="button" name="clickMe" value="Click me and wait!"
onclick="setTimeout('alert('Surprise!')', 5000)"/>

When a visitor clicks the button, the setTimeout() method is called, passing in the expression that we want to run after the time delay, and the value of the time delay itself – 5,000 milliseconds or 5 seconds.

Try it yourself! Click the button below and wait 5 seconds:

It’s worth pointing out that setTimeout() doesn’t halt the execution of the script during the timeout period; it merely schedules the specified expression to be run at the specified time. After the call to setTimeout() the script continues normally, with the timer running in the background.

In the above simple example we embedded the entire code for our JavaScript alert box in the setTimeout() call. More usually, you’d call a function instead. In this next example, clicking a button calls a function that changes the button’s text colour to red. At the same time, this function also sets up a timed function using setTimeout() that sets the text colour back to black after 2 seconds:


<script type="text/javascript">

function setToRed ( )
{
  document.getElementById("colourButton").style.color = "#FF0000";
  setTimeout ( "setToBlack()", 2000 );
}

function setToBlack ( )
{
  document.getElementById("colourButton").style.color = "#000000";
}

</script>

<input type="button" name="clickMe" id="colourButton" value="Click me and wait!" onclick="setToRed()"/>

Click the button below to see it in action:

clearTimeout()

Sometimes it’s useful to be able to cancel a timer before it goes off. The clearTimeout() method lets us do exactly that. Its syntax is:


clearTimeout ( timeoutId );

where timeoutId is the ID of the timeout as returned from the setTimeout() method call.

For example, the following code sets up an alert box to appear after 3 seconds when a button is clicked, but the visitor can click the same button before the alert appears and cancel the timeout:


<script type="text/javascript">

var alertTimerId = 0;

function alertTimerClickHandler ( )
{
  if ( document.getElementById("alertTimerButton").value == "Click me and wait!" )
  {
    // Start the timer
    document.getElementById("alertTimerButton").value = "Click me to stop the timer!";
    alertTimerId = setTimeout ( "showAlert()", 3000 );
  }
  else
  {
    document.getElementById("alertTimerButton").value = "Click me and wait!";
    clearTimeout ( alertTimerId );
  }
}

function showAlert ( )
{
  alert ( "Too late! You didn't stop the timer." );
  document.getElementById("alertTimerButton").value = "Click me and wait!";
}

</script>

<input type="button" name="clickMe" id="alertTimerButton" value="Click me and wait!" onclick="alertTimerClickHandler()"/>

Try it out! Click the button below to start the timer, and click it again within 3 seconds to cancel it.

setInterval()

The setInterval() function is very closely related to setTimeout() – they even share similar syntax:


setInterval ( expression, interval );

The important difference is that, whereas setTimeout() triggers expression only once, setInterval() keeps triggering expression again and again (unless you tell it to stop).

So when should you use it? Essentially, if you ever find yourself writing code like:



setTimeout ( "doSomething()", 5000 );

function doSomething ( )
{
  // (do something here)
  setTimeout ( "doSomething()", 5000 );
}

…then you should probably be using setInterval() instead:



setInterval ( "doSomething()", 5000 );

function doSomething ( )
{
  // (do something here)
}

Why? Well, for one thing you don’t need to keep remembering to call setTimeout() at the end of your timed function. Also, when using setInterval() there’s virtually no delay between one triggering of the expression and the next. With setTimeout(), there’s a relatively long delay while the expression is evaluated, the function called, and the new setTimeout() being set up. So if you need regular, precise timing – or you need to do something at, well, set intervals – setInterval() is your best bet.

clearInterval()

As you’ve probably guessed, if you want to cancel a setInterval() then you need to call clearInterval(), passing in the interval ID returned by the call to setInterval().

Here’s a simple example of setInterval() and clearInterval() in action. When you press a button, the following code displays “Woo!” and “Yay!” randomly every second until you tell it to stop. (I said a simple example, not a useful one.) Notice how we’ve also used a setTimeout() within the wooYay() function to make the “Woo!” or “Yay!” disappear after half a second:


<script type="text/javascript">

var wooYayIntervalId = 0;

function wooYayClickHandler ( )
{
  if ( document.getElementById("wooYayButton").value == "Click me!" )
  {
    // Start the timer
    document.getElementById("wooYayButton").value = "Enough already!";
    wooYayIntervalId = setInterval ( "wooYay()", 1000 );
  }
  else
  {
    document.getElementById("wooYayMessage").innerHTML = "";
    document.getElementById("wooYayButton").value = "Click me!";
    clearInterval ( wooYayIntervalId );
  }
}

function wooYay ( )
{
  if ( Math.random ( ) > .5 )
  {
    document.getElementById("wooYayMessage").innerHTML = "Woo!";
  }
  else
  {
    document.getElementById("wooYayMessage").innerHTML = "Yay!";
  }

  setTimeout ( 'document.getElementById("wooYayMessage").innerHTML = ""', 500 );

}

</script>

<div id="wooYayMessage" style="height: 1.5em; font-size: 2em; color: red;"></div>
<input type="button" name="clickMe" id="wooYayButton" value="Click me!" onclick="wooYayClickHandler()"/>

And here it is in action. Click the button below to kick it off:

Summary

We’ve now covered the four methods that you can use to create timed events in JavaScript: setTimeout() and clearTimeout() for controlling one-off events, and setInterval() and clearInterval() for setting up repeating events. Armed with these tools, you should have no problem creating timed events in your own scripts.

Filed Under: JavaScript Tagged With: countdown, regular, time delays, timed events, trigger, triggering

Reader Interactions

Comments

  1. akeane says

    3 March 2010 at 3:54 am

    Excellent explanation of timers and your examples are great.
    Thank you.

    Reply
  2. matt says

    3 March 2010 at 4:34 pm

    @akeane: Thanks for your kind words. I’m glad you enjoyed the tutorial. πŸ™‚

    Cheers,
    Matt

    Reply
  3. davehardwick says

    10 April 2010 at 2:57 pm

    Another thing to talk about here with setInterval is setting a loop counter and clearing the interval when that loop count is hit.

    
         var counter = 0
         intervalId = 0;
    
         function myLoopFunction()
         {
                   intervalId = setInterval(function() {
                   //make this is the first thing you do in the set interval function
                   counter++;
                    
                  //do you code for setInterval() and clearInterval under normal conditions here...
                  
                 //okay, if we have tried for 5 minutes (30 x 10 seconds ), then lets stop trying because we did not reach the clearInterval under number means
    
               //make this the last check in your set interval function
                if ( counter > 30 ) {
                    clearInterval(polliFrameSourceIntervalId);
                }
     
                 //end setInterval
                } , 10000);
    
    
    
    
    Reply
  4. anupam says

    7 December 2010 at 12:12 am

    Very useful post, and the examples are just superb, thanks, it helped a lot!!

    Reply
  5. matt says

    9 December 2010 at 7:22 pm

    @anupam: Thanks, glad you found it helpful πŸ™‚

    Reply
  6. NT_Jester says

    19 January 2011 at 8:27 am

    I Just want to thank you for such a great and simple to follow tutorial. I have looked at a lot over the past few weeks and I have got to say this is the best one I have seen for ages. Keep up the good work this has helped me heaps.

    Reply
  7. matt says

    20 January 2011 at 2:20 pm

    @NT_Jester: You’re welcome – thanks for the kind words. πŸ™‚ Hope life is good up in the NT!

    Reply
  8. ecommy says

    19 August 2011 at 7:47 am

    Great and detailed explanations, I took the time to create an account just to thank you as it helped debugging a JavaScript issue I had since a while.

    Reply
  9. matt says

    23 August 2011 at 10:41 pm

    @ecommy: Great stuff πŸ™‚

    Reply
  10. froopy says

    8 February 2012 at 8:16 am

    Thank you for this post.
    I was able to modify this for a music writing application.
    I will link back.

    Reply
  11. matt says

    13 February 2012 at 4:10 am

    @froopy: You’re welcome – thanks for the link back πŸ™‚

    Reply
  12. jacky says

    30 April 2012 at 4:10 pm

    thank you for taking the time to create this clear and useful post!

    Reply
  13. frikson says

    6 May 2015 at 6:47 am

    Start a new thread please rather than hijacking this Article discussion.

    Thank You

    [Edited by chrishirst on 06-May-15 10:01]

    Reply
  14. frikson says

    19 May 2015 at 5:39 am

    Hello,

    this is my script

    <script>function setToRed ( ) { document.getElementById("moondoge").style.backgroundColor = "#FF0000";
      setTimeout ( "setToBlack()", 10000 );
    } function setToBlack ( )
    { document.getElementById("moondoge").style.backgroundColor= "#009933";
    }
    </script>
    
    <script>function setToRed ( ) { document.getElementById("freedoge").style.backgroundColor = "#FF0000";
      setTimeout ( "setToBlack()", 20000 );
    } function setToBlack ( )
    { document.getElementById("freedoge").style.backgroundColor= "#009933";
    }
    </script>
    

    and this is my html

    <a href="http://moondoge.co.in/"  target="_blank">
    <input type="button" name="clickMe" id="moondoge" value="Moon Doge" onclick="setToRed()"/>
    
    <a href="https://freedoge.co.in"  target="_blank">
    <input type="button" name="clickMe" id="freedoge" value="Free Doge" onclick="setToRed()"/>
    

    After click on a moondoge button the second button changes the color into red and not the moondoge.

    Any suggestions?

    Thanks in advance

    Reply
  15. chrishirst says

    19 May 2015 at 5:05 pm

    Just look at it logically, you have two function sets, BOTH sets of functions have the same names, which is going to be called when you “click” one of the buttons?

    Reply
  16. frikson says

    19 May 2015 at 6:36 pm

    Hello Chris, thanks for your replay.
    I’m sorry, but I’m a totally new in this script/html language. I know that it sound crazy, but I really don’t know what you mean.
    I try to add 1 at the end of function setToRed1( ) …

    <script type="text/javascript">
    <script>function setToRed(  ) { document.getElementById("moondoge").style.backgroundColor = "#FF0000";
      setTimeout ( "setToBlack()", 10000 );
    } function setToBlack (  )
    { document.getElementById("moondoge").style.backgroundColor= "#009933";
    }
    </script>
    
    <script>function setToRed1(  ) { document.getElementById("freedogecoin").style.backgroundColor = "#FF0000";
      setTimeout ( "setToBlack()", 10000 );
    } function setToBlack (  )
    { document.getElementById("freedogecoin").style.backgroundColor= "#009933";
    }
    </script>
    

    html code

    <a class="button" href="http://moondoge.co.in/"  target="_blank"><input type="button" name="clickMe" id="moondoge" value="Moon Doge" onclick="setToRed( )"/>
    
    <a href="http://freedoge.co.in"  target="_blank">
    <input type="button" name="clickMe" id="freedogecoin" value="Free Doge Coin" onclick="setToRed1( )"/>
    

    First button doesn’t change the color at all, the second button Free Doge Coin works perfectly.

    When I try to add the 3rd button

    <script>function setToRed2(  ) { document.getElementById("dogefree").style.backgroundColor = "#FF0000";
      setTimeout ( "setToBlack()", 10000 );
    } function setToBlack (  )
    { document.getElementById("dogefree").style.backgroundColor= "#009933";
    }
    </script>
    
    <a href="http://dogefree.net/"  target="_blank">
    <input type="button" name="clickMe" id="dogefree" value="Doge Free" onclick="setToRed2( )"/>
    

    The second button changes the color into red, but after 10 sec. the 3rd button changes color to green and not the second one. The second button is red all the time, now the 3rd button works perfectly.
    I’m totally confuse.

    I have 38 buttons to set to work this way.
    Could you, please, correct my code/function set to work perfectly, I will be very grateful.

    Reply
  17. froopy says

    20 May 2015 at 11:29 pm

    Just use one set of functions, one to red and one to black. Pass the name of the buttons when you call the function.

    <script>
    var dogebutton="";
    function setToRed (dogebutton) { 
    document.getElementById(dogebutton).style.backgroundColor = "#FF0000";
    setTimeout(function(){ setToBlack(dogebutton) }, 10000);
    } 
    function setToBlack (dogebutton){ 
    document.getElementById(dogebutton).style.backgroundColor= "#009933";
    }
    </script>
    
    
    
    <a href="http://froopysnotebook.com/"  target="_blank">
    <input type="button" name="clickMe" id="moondoge" value="Moon Doge" onclick="setToRed('moondoge')"/>
    
    <a href="http://froopysnotebook.com/pr"  target="_blank">
    <input type="button" name="clickMe" id="freedoge" value="Free Doge" onclick="setToRed('freedoge')"/>
    
    
    Reply
  18. frikson says

    21 May 2015 at 11:51 am

    Many many thanks for your reply, froopy, it works perfectly.

    I just forgot to mention that I have different time interval for different buttons; 90 sec. for Moon Doge, 60 sec. for Free Doge, 10 min. for …
    I have 10 buttons with 90 sec. interval,
    20 buttons with 60 sec. interval,
    15 buttons with 10 minutes interval, …

    I guess that I have to add some additional function and I try it, but it’s not working.
    Could you help me with this, please!

    Reply
  19. chrishirst says

    21 May 2015 at 5:25 pm

    You pass values to ONE function as parameters, and those values determine which element they affect or manipulate and how they it.

    I’m going to write a full answer with examples at my forum simply because it has much better editing tools and I can write a whole article rather than a cramped up forum post and I will provide a link to the article here.

    With any luck it will be a quiet Friday and I’ll had it done for late tomorrow.

    I’ll be back!

    Reply
  20. frikson says

    21 May 2015 at 6:25 pm

    Great, thanks in advance.

    Have a nice day!

    Reply
  21. chrishirst says

    22 May 2015 at 6:02 pm

    Bit later than anticipated, but

    http://webmaster-talk.eu/articles/8-website-development-and-design/45-javascript-functions-write-once-use-many

    Reply
  22. sajjadhira says

    30 August 2017 at 6:24 am

    This is an example of JavaScript automatic popup closing after 10 seconds with countdown,

    <p style="text-align:center">This window will close automatically within <span id="counter">10</span> second(s).</p>
    <script type="text/javascript">
    
    
    
     function countdown() {
    
        var i = document.getElementById('counter');
    
        i.innerHTML = parseInt(i.innerHTML)-1;
    
     if (parseInt(i.innerHTML)<=0) {
    
      window.close();
    
     }
    
    }
    
    setInterval(function(){ countdown(); },1000);
    
    </script>
    

    I have found it into PHPAns Forum. Hope this will be helpful for you.

    [Edited by sajjadhira on 30-Aug-17 06:25]

    Reply
  23. Roelf Keulder says

    6 September 2021 at 8:59 pm

    Thank you for your detailed and easy to understand post.
    Can I use either one of these functions to extend the time on a timer running by clicking on a button

    Reply
    • Matt Doyle says

      13 September 2021 at 6:48 am

      Not directly – once a timer is started, it runs until it finishes (or is cleared).

      What you could do is use setInterval() with a 1-second interval to call a function that updates a countdown value (assuming you want to count down in seconds). Then your button would simply change this countdown value in order to extend the time.

      Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

To include a block of code in your comment, surround it with <pre> ... </pre> tags. You can include smaller code snippets inside some normal text by surrounding them with <code> ... </code> tags.

Allowed tags in comments: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre> .

Primary Sidebar

Hire Matt!

Matt Doyle headshot

Need a little help with your website? I have over 20 years of web development experience under my belt. Let’s chat!

Matt Doyle - Codeable Expert Certificate

Hire Me Today

Call Me: +61 2 8006 0622

Stay in Touch!

Subscribe to get a quick email whenever I add new articles, free goodies, or special offers. I won’t spam you.

Subscribe

Recent Posts

  • Make a Rotatable 3D Product Boxshot with Three.js
  • Speed Up Your WordPress Website: 11 Simple Steps to a Faster Site
  • Reboot!
  • Wordfence Tutorial: How to Keep Your WordPress Site Safe from Hackers
  • How to Make Awesome-Looking Images for Your Website

Footer

Contact Matt

  • Email Me
  • Call Me: +61 2 8006 0622

Follow Matt

  • E-mail
  • Facebook
  • GitHub
  • LinkedIn
  • Twitter

Copyright © 1996-2023 Elated Communications. All rights reserved.
Affiliate Disclaimer | Privacy Policy | Terms of Use | Service T&C | Credits