Difference Between the JavaScript's setTimeout() and setInterval() Functions
In this article, you will learn the Difference Between JavaScript's setTimeout() and setInterval() functions. The main purpose of this tutorial is to give the IT/CS students and new programmers a reference to understand the usage and when to use the said JavaScript Functions. Here, snippets and a sample application source code that demonstrate the functionality of setTimeout and setInterval are provided.
What is the Difference Between JavaScript's setTimeout() and setInterval()?
JavaScript's setTimeout() and setInterval() functions have the same syntax of coding but different use. The setTimeout() executes an expression or a script once while the setInterval() executes the expression or script repeatedly. Check out the snippet below to have a better understanding.
Using JS setTimeout()
The below snippet demonstrates a simple setTimeout() script. It executes the certain script after the given timeout and it is only done once.
- window.load = function(){
- setTimeout(()=>{
- alert("This is a sample message");
- },3000)
- }
When you add the script above to your web application, an alert/dialog will be shown 3 seconds after the page document is successfully loaded.
Using JS setTinterval()
The below snippet demonstrates how the setInteval() function works.
- window.load = function(){
- setInterval(()=>{
- location.reload();
- },10000)
- }
Adding the simple script above to your web application enables your application to refresh or reload 10 seconds after the page document is successfully loaded.
When to use JavaScript's setTimeout() and setInterval()?
The setTimeout() and setInterval() usage depends on what logic you are targeting to create on your application client side. If you like to delay the execution of the script on your application and run it only once, setTimeout() is the best option for doing it. If you like to repeatedly execute a JS function or script, the setInterval() method is the best option. Also, to stop the interval, use the clearInterval() method.
Example
Here's a simple web application source code that demonstrates the usage of both setTimeout() and setInterval() methods.
Interface
index.html
- <!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">
- <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/css/all.min.css" integrity="sha512-xh6O/CkQoPOWDdYTDqeRdPCVd1SpvCA9XXcUnZS2FmJNp1coAFzvtCN9BmamE+4aHK8yyUHUSCcJHgXloTyT2A==" crossorigin="anonymous" referrerpolicy="no-referrer" />
- <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous">
- <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-OERcA2EqjJCMA+/3y+gxIOqMEjwtxJY7qPCqsdltbNJuaOe923+mo//f6V8Qbsw3" crossorigin="anonymous"></script>
- <style>
- html, body{
- height: 100%;
- width: 100%;
- }
- body{
- display: flex;
- height: 100%;
- width: 100%;
- flex-direction: column;
- }
- body>nav, body>footer{
- flex-shrink: 1;
- }
- body>main{
- flex-shrink: 1;
- flex-grow: 1;
- overflow: auto;
- display: flex;
- flex-direction: column;
- width: 100%;
- align-items: center;
- justify-content: center;
- }
- pre{
- min-height:20vh
- }
- .bigFont{
- font-size:20px;
- }
- </style>
- </head>
- <body style="background:#eff3fc">
- <nav class="navbar navbar-expand-lg navbar-dark" style="background:#495C83">
- <div class="container">
- <div>
- </div>
- </div>
- </nav>
- <main class="container-fluid">
- <div class="col-lg-6 col-md-8 col-sm-12 mx-auto">
- <hr>
- <div class="card mt-3 rounded-0">
- <div class="card-body rounded-0">
- <div class="container-fluid">
- <div class="row justify-content-center">
- <div class="col-lg-8 col-md-10 col-sm-12 col-xs-12">
- <div class="mb-3 text-center" id="displayContainer">
- </div>
- <div class="mb-3">
- <div class="row">
- <div class="col-lg-6 col-md-6 col-sm-12">
- </div>
- <div class="col-lg-6 col-md-6 col-sm-12">
- </div>
- </div>
- </div>
- </div>
- </div>
- </div>
- </div>
- </div>
- </div>
- </main>
- <footer class="container-fluid py-3" style="background:#495C83; color:#fff">
- <div class="container-fluid my-2">
- <div class="text-center">
- </div>
- </div>
- </footer>
- </body>
- </html>
JavaScript
assets/script.js
- const settimeoutBtn = document.getElementById('settimeoutBtn')
- const setintervalBtn = document.getElementById('setintervalBtn')
- const displayContainer = document.getElementById('displayContainer')
- /**
- * setTimeout Example Script
- * syntax
- * setTimeout(expression, timeout)
- * - timeout = (1 second = 1000)
- */
- settimeoutBtn.addEventListener('click', function(){
- displayContainer.innerText = "Please wait for 5 seconds."
- setTimeout(()=>{
- displayContainer.innerText = ""
- alert("You have waited 5 second before this dialog been shown.")
- }, 5000)
- })
- /**
- * setInterval Example Script
- * syntax
- * setInterval(expression, timeout)
- * - timeout = (1 second = 1000)
- */
- var interval;
- setintervalBtn.addEventListener('click', function(){
- var is_started = setintervalBtn.getAttribute('is-started')
- if(is_started == null || is_started == "false"){
- setintervalBtn.setAttribute('is-started',"true")
- is_started = true
- setintervalBtn.innerText = "Stop Interval"
- displayContainer.classList.add('bigFont')
- }else{
- displayContainer.classList.remove('bigFont')
- setintervalBtn.setAttribute('is-started',"false")
- is_started = false
- setintervalBtn.innerText = "setInterval"
- }
- if(is_started){
- displayContainer.innerText = 0
- var countdown = parseInt(displayContainer.innerText)
- interval = setInterval(()=>{
- countdown++;
- displayContainer.innerText = countdown
- }, 1000)
- }else{
- if(interval != undefined)
- clearInterval(interval)
- }
- })
The source code above will result in a simple web application page that contains 2 buttons. One of the buttons triggers/displays an alert dialog after 5 seconds. The other one is to trigger a simple countdown.
Snapshots
There you go. That's the end of this tutorial. I hope this setTimeout() vs setInterval() of JavaScript Tutorial will help you with what you are looking for and adds up to your knowledge of using JavaScript built-in methods.
Explore more on this website for more Tutorials and Free Source Codes.
Happy Coding =)
Add new comment
- 219 views