JavaScript setTimeout and setInterval

Leave a comment

In JavaScript, we can use setTimeout() to call a function after waiting for a specified number of milliseconds. We can provide a callback function to as well as the timeout as parameters. For example, let’s say we want to print to the console “Hello World” after waiting 2 seconds. To do this:

    setTimeout(function(){ 
        console.log("Hello World"); }, 2000);

This will wait for 2 seconds before printing to the console:

If we run timeouts as below they will start sequentially and then run. JavaScript treats this as an asynchronous and non-blocking. So below:

    setTimeout(function(){ 
        console.log("Hello World"); }, 2000);

        setTimeout(function(){ 
        console.log("Hello World"); }, 3000);

        setTimeout(function(){ 
        console.log("Hello World"); }, 4000);

Produces after 2, 3, 4 seconds:

To prevent setTimeout() from running, use clearTimeout(). For example, below:

    var t = setTimeout(function(){ 
        console.log("Hello World 1"); }, 2000);
    
    clearTimeout(t);

        setTimeout(function(){ 
        console.log("Hello World 2"); }, 3000);

Will print:

By contrast, setInterval() will continually run until clearInterval() is called. For example below, setInterval() will run indefinitely, but we will call clearInterval() after 10 seconds:

      var t = setInterval(function(){ 
        console.log("Hello World"); }, 1000);
    
        setTimeout(function(){ 
            clearInterval(t); }, 10000);

This produces:

 

THANKS FOR READING. BEFORE YOU LEAVE, I NEED YOUR HELP.
 

I AM SPENDING MORE TIME THESE DAYS CREATING YOUTUBE VIDEOS TO HELP PEOPLE LEARN THE MICROSOFT POWER PLATFORM.

IF YOU WOULD LIKE TO SEE HOW I BUILD APPS, OR FIND SOMETHING USEFUL READING MY BLOG, I WOULD REALLY APPRECIATE YOU SUBSCRIBING TO MY YOUTUBE CHANNEL.

THANK YOU, AND LET'S KEEP LEARNING TOGETHER.

CARL

https://www.youtube.com/carldesouza

 

ABOUT CARL DE SOUZA

Carl de Souza is a developer and architect focusing on Microsoft Dynamics 365, Power BI, Azure, and AI.

carldesouza.comLinkedIn Twitter | YouTube

 

Leave a Reply

Your email address will not be published. Required fields are marked *