How to call a function repeatedly after fixed time interval in jQuery

Topic: JavaScript / jQuery« Prev|Next »

Answer: Use the JavaScript setInterval() method

You can use the JavaScript setInterval() method to execute a function repeatedly after a certain time period. The setInterval() method requires two parameters first one is typically a function or an expression and the other is time delay in milliseconds.

In the following example the showTime() function is called repeatedly after every 1000 milliseconds (i.e. 1 second) until you tell it to stop.

  • <!DOCTYPE html>
  • <html lang="en">
  • <head>
  • <meta charset="UTF-8">
  • <title>The JavaScript setInterval() Method</title>
  • <script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
  • <script type="text/javascript">
  • var myVar;    
  • function showTime(){
  •     var d = new Date();
  •     var t = d.toLocaleTimeString();
  •     $("#demo").html(t); // display time on the page
  • }
  • function stopFunction(){
  •     clearInterval(myVar); // stop the timer
  • }
  • $(document).ready(function(){
  •     myVar = setInterval("showTime()", 1000);
  • });
  • </script>
  • </head>
  • <body>
  •     <p id="demo"></p>
  •     <button onclick="stopFunction()">Stop Timer</button>
  • </body>
  • </html>

However, a better approach is using the setTimeout() function if you are doing some time consuming stuff. Because, unlike the setInterval() with setTimeout() function you can wait till function is executed completely before calling it again.

  • <!DOCTYPE html>
  • <html lang="en">
  • <head>
  • <meta charset="UTF-8">
  • <title>The JavaScript setTimeout() Method</title>
  • <style type="text/css">
  •     img{
  •         display: none;
  •     }
  • </style>
  • <script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
  • <script type="text/javascript">
  • var myVar;    
  • function showImage(){
  •     $("img").fadeIn(750).fadeOut(750);
  •     myVar = setTimeout(showImage, 2000);
  • }
  • function stopFunction(){
  •     clearTimeout(myVar); // stop the timer
  • }
  • $(document).ready(function(){
  •     showImage();
  • });
  • </script>
  • </head>
  • <body>
  •     <button onclick="stopFunction()">Stop Image Transition</button>
  •     <p>
  •         <img src="images/sky.jpg" alt="Cloudy Sky">
  •     </p>
  • </body>
  • </html>

In the example above the showImage() function is called every time after 2000 milliseconds (i.e. 2 seconds) once the image fade in and fade out transition has been fully completed.


Related FAQ

Here are some more FAQ related to this topic:

 
Close

Your Feedback:

 

We would love to hear from you! Please say something.