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