Delay and Loop Function Call with setTimeout and setInterval in JavaScript

Delaying and looping function calls can be a useful tool when creating interactive web applications. By using the setTimeout and setInterval functions, you can create dynamic effects that can enhance the user experience.

Both setTimeout() and setInterval() methods provide us a good way to control when to call a function when writing in JavaScript.

Table of Contents

setTimeout()

The method calls a function or evaluates an expression after a specified number of milliseconds.

setTimeout( function(){ lookup(); }, 5000 );

function lookup(){
	$.ajax({
       url: 'notification/lookup',       
       type: 'GET',
       dataType: 'json',
       error: function() {
          
       },
       success: function(result) { 
       }
   });
}

Note: To prevent the function from running we use the clearTimeout() method.

setInterval()

The method calls a function or evaluates an expression at specified intervals in milliseconds.

setInterval( function(){ lookup_period(); }, 10000 );

function lookup_period(){
	$.ajax({
       url: 'notification/lookup_period',       
       type: 'GET',
       dataType: 'json',
       success: function(result) { 
       	if (result.success){
       		//do something
       	}
       }
   });
}

Note: The clearInterval() method is used to stop setInterval() from continuously running.

var i = 0;
intervalId = setInterval( function(){
	console.log('testing: ' + i); 		
	i++;
	if (i > 100){
		clearInterval(intervalId);	
	}			
}, 3000 );

Leave a Comment

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


Scroll to Top

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close