JavaScript tutorials for Beginners – Javascript setInterval()

Hits: 45

 

(JavaScript Tutorials for Beginners)

In this end-to-end example, you will learn – JavaScript tutorials for Beginners – Javascript setInterval().

 

Javascript setInterval()

In this tutorial, you will learn about the JavaScript setInterval() method with the help of examples.

In JavaScript, a block of code can be executed in specified time intervals. These time intervals are called timing events.

There are two methods for executing code at specific intervals. They are:

  • setInterval()
  • setTimeout()

In this tutorial, you will learn about the setInterval() method.


JavaScript setInterval()

The setInterval() method repeats a block of code at every given timing event.

The commonly used syntax of JavaScript setInterval is:

setInterval(function, milliseconds);

Its parameters are:

  • function – a function containing a block of code
  • milliseconds – the time interval between the execution of the function

The setInterval() method returns an intervalID which is a positive integer.


Example 1: Display a Text Once Every 1 second

// program to display a text using setInterval method
function greet() {
    console.log('Hello world');
}

setInterval(greet, 1000);

Output

Hello world
Hello world
Hello world
Hello world
Hello world
....

In the above program, the setInterval() method calls the greet() function every 1000 milliseconds(1 second).

Hence the program displays the text Hello world once every 1 second.

Note: The setInterval() method is useful when you want to repeat a block of code multiple times. For example, showing a message at a fixed interval.


Example 2: Display Time every 5 seconds

// program to display time every 5 seconds
function showTime() {

    // return new date and time
    let dateTime= new Date();

    // return the time
    let time = dateTime.toLocaleTimeString();

    console.log(time)
}

let display = setInterval(showTime, 5000);

Output

"5:15:28 PM"
"5:15:33 PM"
"5:15:38 PM"
....

The above program displays the current time once every 5 seconds.

newDate() gives the current date and time. And toLocaleTimeString() returns the current time. To learn more about date and time, visit JavaScript Date and Time.


JavaScript clearInterval()

As you have seen in the above example, the program executes a block of code every specified time interval. If you want to stop this function call, then you can use the clearInterval() method.

The syntax of clearInterval() method is:

clearInterval(intervalID);

Here, the intervalID is the return value of the setInterval() method.


Example 3: Use clearInterval() Method

// program to stop the setInterval() method after five times

let count = 0;

// function creation
let interval = setInterval(function(){

    // increasing the count by 1
    count += 1;

    // when count equals to 5, stop the function
    if(count === 5){
        clearInterval(interval);
    }

    // display the current time
    let dateTime= new Date();
    let time = dateTime.toLocaleTimeString();
    console.log(time);

}, 2000);

Output

4:47:41 PM
4:47:43 PM
4:47:45 PM
4:47:47 PM
4:47:49 PM

In the above program, the setInterval() method is used to display the current time every 2 seconds. The clearInterval() method stops the function call after 5 times.


You can also pass additional arguments to the setInterval() method. The syntax is:

setInterval(function, milliseconds, parameter1, ....paramenterN);

When you pass additional parameters to the setInterval() methods, these parameters (parameter1parameter2, etc.) will be passed to the specified function.

For example,

// program to display a name
function greet(name, lastName) {
    console.log('Hello' + ' ' + name + ' ' + lastName);
}

// passing argument to setInterval
setInterval(greet, 1000, 'John', 'Doe');

Output

Hello John Doe
Hello John Doe
Hello John Doe
....

In the above program, two parameters John and Doe are passed to the setInterval() method These two parameters are the arguments that will be passed to the function that is defined inside the setInterval() method.


Note: If you only need to execute a function one time, it’s better to use the setTimeout() method.

 

Personal Career & Learning Guide for Data Analyst, Data Engineer and Data Scientist

Applied Machine Learning & Data Science Projects and Coding Recipes for Beginners

A list of FREE programming examples together with eTutorials & eBooks @ SETScholars

95% Discount on “Projects & Recipes, tutorials, ebooks”

Projects and Coding Recipes, eTutorials and eBooks: The best All-in-One resources for Data Analyst, Data Scientist, Machine Learning Engineer and Software Developer

Topics included: Classification, Clustering, Regression, Forecasting, Algorithms, Data Structures, Data Analytics & Data Science, Deep Learning, Machine Learning, Programming Languages and Software Tools & Packages.
(Discount is valid for limited time only)

Disclaimer: The information and code presented within this recipe/tutorial is only for educational and coaching purposes for beginners and developers. Anyone can practice and apply the recipe/tutorial presented here, but the reader is taking full responsibility for his/her actions. The author (content curator) of this recipe (code / program) has made every effort to ensure the accuracy of the information was correct at time of publication. The author (content curator) does not assume and hereby disclaims any liability to any party for any loss, damage, or disruption caused by errors or omissions, whether such errors or omissions result from accident, negligence, or any other cause. The information presented here could also be found in public knowledge domains.

Learn by Coding: v-Tutorials on Applied Machine Learning and Data Science for Beginners

Please do not waste your valuable time by watching videos, rather use end-to-end (Python and R) recipes from Professional Data Scientists to practice coding, and land the most demandable jobs in the fields of Predictive analytics & AI (Machine Learning and Data Science).

The objective is to guide the developers & analysts to “Learn how to Code” for Applied AI using end-to-end coding solutions, and unlock the world of opportunities!