Search

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

post-title

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. Let's try it out and see how it works:

<!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>
    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. Here's an example:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>The JavaScript setTimeout() Method</title>
<style>
    img{
        display: none;
    }
</style>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script>
    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>