DONATE  
MENU
MYSQL
HTML
JAVASCRIPT
AJAX
CSS
JSON
PHP

JavaScript Tutorials

INTRODUCTION

» Introduction to JavaScript

» Practice IT Editor

» JavaScript Example

» JavaScript Placement

» JavaScript Syntax

» JavaScript Statements

» JavaScript Input

» JavaScript Output

» JavaScript Comments

» JavaScript Variables

» Variables' Scope

» JavaScript Operators

» JS Expressions & Concatenation

» JavaScript Data Type

» JavaScript Numbers

» Number Object

» JavaScript Strings

» String Object

» JavaScript Booleans

» Boolean Object

» JavaScript Functions

» JavaScript Arrays

» Array Object - Properties

» Array Object - Methods

» JavaScript Objects

» JavaScript Undefined

» JavaScript Nulls

CONDITIONAL TESTING

» If Statement

» If Else Statement

» JavaScript Ternary Operator

» Switch Statement

LOOPS

» For Loops

» While Loops

» Break & Continue

» For...In Loops

» do...while Loop

FUNCTIONS

» JavaScript Functions

» Creating Functions

» Functions' Parameters

» Functions' Arguments

» Function Invocation

» The Return Keyword

» The Arguments Object

» Callback Functions

» Arrow Functions

ARRAYS

» JavaScript Arrays

» Creating Arrays

» Accessing Arrays

» Looping Arrays

» Multi - dimensional Arrays

OBJECTS

» JavaScript Objects

» Creating Objects

» Prototype Definition

» Accessing Objects

» The this Keyword

AJAX

» Introduction to AJAX

JSON

» Introduction to JSON

JAVASCRIPT DATES

» The Date Object

» Date Methods

» Timing (SetInterval & SetTimeout)

MATH OBJECT

» Math Object

» Math Methods

HTML / JS DOM

» DOM Introduction

» Accessing HTML Elements in DOM

» Get And Change Elements' Contents & Values

» Change Styling - DOM CSS

» DOM Attributes

» JavaScript Event Listeners

» DOM Event Listeners

» JS Events

MISCELLANEOUS

» JS Strict Mode

» JavaScript Hoisting

» JavaScript let keyword

» Reserved Keywords

» JS Best Practices

» JavaScript vs ECMAScript

JAVASCRIPT EXAMPLES

» JavaScript Calculator

.. » JavaScript » Javascript Dates » Timing (SetInterval & SetTimeout)
Share Tweet WhatsApp

Timing (SetInterval & SetTimeout)

The timing functions are functions that enables us to dictate when a function or set of codes or statements should be executed. These functions allow us to give a time frame upon whose elapse will lead to the execution of a function. For example, invoking a function to deduct 1 from a number after every 30seconds. The most important functions usually used in JavaScript timing are the setInterval() and setTimeout(). setInterval() The setInterval() function allows us to continuously execute a function after a set period of time. For example, continuous deduction of 1 from a number every 3 seconds. The function accepts two arguments. First, a callback function which is the function to be executed after the time frame elapses and the second is the number of milliseconds to wait before each execution. Remember, 1000 milliseconds makes 1 second.
<h1>60</h1>
<script>
setInterval(deduct, 3000); //Set interval to execute a function every 3 seconds

function deduct(){
var numEl = document.querySelectorAll("h1")[0]; //Object of element containing the number
var num = parseInt(numEl.innerText) - 1; //Obtaining the number text inside the element and parsing it into a number. We also deducted 1 from it
numEl.innerText = num; //Displaying the new number
}
</script>

Copy PRACTICE IT

You can also define statements to execute directly as the first argument of the setInterval() without necessary having to define such in another function. We can make use of anonymous functions in this case.
<h1>0</h1>
<script>
setInterval(//Define statements inside anonymous function
function (){
var numEl = document.querySelectorAll("h1")[0]; //Object of element containing the number
var num = parseInt(numEl.innerText) + 1; //Obtaining the number text inside the element and parsing it into a number. We also added 1 to it
numEl.innerText = num; //Displaying the new number
}, 3000);
</script>

Copy PRACTICE IT

Using anonymous functions, you can also invoke other function(s). The anonymous function is specially important if the suppose callback function has some parameters that need to be assign during invocation.
setInterval(function (){
doSomething(); //invoking a function inside an anonymous function
doTheThing("arg"); //invoking a function with argument inside an anonymous function
}, 1000); //every 1 second
clearInterval() The clearInterval() function enables us to stop the continuous execution of a function that had been set using the setInterval(). That is, it stops the setInterval() from further execution. For example, deducting 1 from a number using the setInterval() and stopping it using the clearInterval() when the number gets to 0. To achieve this, you should invoke the setInterval() on a variable and assign that variable to the clearInterval() as an argument.
<h1>60</h1>
<button onclick='clr()'>STOP</button>
<script>
var interval = setInterval(deduct, 3000);
 
//Define callback function
function deduct(){
var numEl = document.querySelectorAll("h1")[0]; //Object of element containing the number
var num = parseInt(numEl.innerText) - 1; //Obtaining the number text inside the element and parsing it into a number. We also deducted 1 from it
numEl.innerText = num; //Displaying the new number
}

//function to clear interval when button is clicked
function clr(){
clearInterval(interval);
}
</script>

Copy PRACTICE IT

Above, we have a button which when clicked invokes a function to stop a timing. setTimeout() The setTimeout() is almost similar to the setInterval(). The major difference is that setInterval() is continuous while the setTimeout() executes once. For example, using the setTimeout() to delay the execution of a function for a specified period.
<p id='myp'>Please wait...5 seconds</p>

<script>
setTimeout(doSomething, 5000); //a time out for 5 seconds

function doSomething(){
document.getElementById("myp").innerText = "Success";
}
</script>

Copy PRACTICE IT

As you can see, the setTimeout() possesses same logic as the setInterval() but unlike the setInterval(), it executes once not continuously. clearTimeout() The clearTimeout() is to the setTimeout() what the clearInterval() is to the setInterval(). It enables you to clear a setTimeout() before it actually executes. For example, using a setTimeout() to execute codes to delete a file after 1 minute and then, an option to abort before the time. Just like the processes involve in using the clearInterval(), you need invoke the setTimeout() on a variable and assign that variable as argument when involving the clearTimeout().
<p id='myp'>Please wait while file is prepared for deletion...</p>
<button onclick='canc()'>CANCEL</button>
<script>
var timeout = setTimeout(deletemsg, 5000); //timeout after 5seconds

function deletemsg(){
document.getElementById("myp").innerText = "File successfully deleted";
}

function canc(){
clearTimeout(timeout);
document.getElementById("myp").innerText = "Request cancelled.";
}
</script>

Copy PRACTICE IT

SUMMARY
  1. There are functions that allows you delay the execution of a function or statements in a function. For the purpose of this tutorial, we called them "timing" functions.
  2. These functions shouldn't be liken to looping. Looping is the continuous execution of a code block without regard to time. This means a code block can be executed 1million times under 1 millisecond.
  3. The setInterval() function allows us to set a time in which a function will continue to execute whenever the time elapses.
  4. To remove the setInterval() at any given point, we make use of the clearInterval().
  5. The setTimeout() is similar to the setInterval() but it is not continuous. It can be liken to delaying the execution of a function just once.
  6. The clearTimeout() also enables to remove a setTimeout() before execution since it executes once.
  7. To work with the setInterval() and setTimeout(), you need to understand milliseconds because you specify their time in milliseconds. Therefore, remember a second is 1000 milliseconds and 1 minute will be 60000 milliseconds since we have 60 seconds in a minute.
  8. The timing functions are actually methods of the window object though they can be use without the window object. Nevertheless window.setInterval() is equivalent to setInterval(). Same applies to the rest.
Take a short quiz on Timing (SetInterval & SetTimeout).
Ask a question or tell us if Timing (SetInterval & SetTimeout) is easy or not.
cent?

Join our 1,090 subscribers to receive tutorials' updates!

  We won't spam your mail box. We hate it.





StackBeginner 2021 © Joseph Omamode