What's the easiest way to call a function every 5 seconds in jQuery?

Let's see how to call a function after every set interval of time using jQuery?
Submitted by Pratishtha Saxena, on November 04, 2022

jQuery helps to make the document more dynamic by adding various features and properties to it. There are various inbuilt functions and methods for this. Now, in order to call a function to get executed we need to use the jQuery setInterval() method.

The setInterval() method of jQuery helps us to repeatedly call the specified function until it is forced to stop. This method delays the execution of the code by the time specified. A particular time interval can be given as per the requirement. The method used to stop the setInterval() method is the clearInterval() method.

Syntax:

setInterval(function(), delay);

It takes in two basic parameters, namely – function and the time delay. The function is the set of code to be executed when setInterval() is called. The time to be delayed is given in milliseconds. Hence, for 5 seconds, we need to pass 5000 as a numeric value for it. The following example shows how the function is executed after every 5 seconds once the button is clicked by the user.

jQuery example to demonstrate the easiest way to call a function every 5 seconds

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <title>Document</title>
  </head>

  <body>
    <h2>Easiest Way To Call A Function After Every 5 Seconds in jQuery</h2>
    <p>Click the button to call the function .</p>
    <button>Start</button>
    <hr>
    <div></div>
    <hr>
  </body>
  
  <script type="text/javascript">
    $(document).ready(function(){
        function print(){
            $('div').append('Executed. ');
        }
        $('button').click(function(){
            var interval = setInterval(print,5000);
        });
    });
  </script>
</html>

Output:

Example 1: Easiest way to call a function every 5 seconds

ADVERTISEMENT
ADVERTISEMENT




Comments and Discussions!




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.