【JS】 Periodically Run a Function
>
>
【JS】 Periodically Run a Function

JS - Periodically Run a Function

JS - Periodically Run a Function

Are you looking to automate tasks on your website, like updating live data or refreshing content without user intervention? JavaScript can help you accomplish this by periodically running a specific function at predefined intervals. In this post, we’ll explore how to achieve this with two code examples and step-by-step explanations.

Table of - contents

No.
Title
1
Code Example 1 Using setInterval
2
Code Example 2 Using setTimeout Recursively
3
Conclusion

Example - 1. Using setInterval

<!DOCTYPE html>
<html>
<head>
    <title>Periodic Function Execution</title>
</head>
<body>
    <p id="output">This text will be updated periodically.</p>
    
    <script>
        function updateText() {
            const element = document.getElementById('output');
            element.innerHTML = `Updated at ${new Date()}`;
        }
        
        // Call updateText function every 3 seconds (3000 milliseconds)
        setInterval(updateText, 3000);
    </script>
</body>
</html>
In this example, we use the ‘setInterval’ function to repeatedly call the ‘updateText’ function every 3 seconds. This function updates the content of a paragraph with the current date and time.

Example - 2. Using setTimeout Recursively

<!DOCTYPE html>
<html>
<head>
    <title>Periodic Function Execution</title>
</head>
<body>
    <p id="output">This text will be updated periodically.</p>
    
    <script>
        function updateText() {
            const element = document.getElementById('output');
            element.innerHTML = `Updated at ${new Date()}`;
        }
        
        // Call updateText function every 3 seconds (3000 milliseconds)
        setInterval(updateText, 3000);
    </script>
</body>
</html>
In this example, we use a combination of ‘setTimeout’ and recursion to achieve periodic execution. The ‘updateText’ function updates the content and then schedules itself to run again after 3 seconds, creating a loop.

3 - Conclusion.

Running a function periodically in JavaScript is a powerful way to automate tasks and keep your website content up to date. You can choose between ‘setInterval’ for a straightforward approach or ‘setTimeout’ with recursion for more control. Experiment with these techniques to enhance user experience and streamline your website’s functionality. Happy coding!
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

Search

.
Xiao. tian
.

Piano - Music

.

Recent - Post

.
0 0 votes
Article Rating

Start typing and press Enter to search

Shopping Cart
0
Would love your thoughts, please comment.x
()
x