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.
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 );