Home › Dynamics 365 Customer Engagement (CRM) › JavaScript setTimeout and setInterval
Dynamics 365 Customer Engagement (CRM) · Sep 25, 2015

JavaScript setTimeout and setInterval

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:

 

Leave a Reply

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

Carl de Souza
KEEP LEARNING. KEEP BUILDING.

Explore AI, agents & Microsoft technology.

I share practical ideas, tutorials, and videos about AI, AI agents, Microsoft technologies, and the Power Platform.