The 2 timer methods of JavaScript that are widely used in jQuery are setTimeout() and setInterval().
These 2 methods allow execution of a code at specified time intervals.
Let us understand these 2 timer methods with codes.
This timer method allows to run a function once after an interval of time.
Syntax:
setTimeout(function, milliseconds, paramerter1, parameter2, ...)
Parameter | Description |
---|---|
Function | Required. The function that will be executed |
Milliseconds | Optional. The number of milliseconds to wait before executing the code. If omitted, the value 0 is used |
paramerter1, paramerter2, … | Optional. Additional parameters to pass to the function |
setTimeout(function(){ alert("Hi"); }, 2000);
You can also separate the function call from the syntax.
setTimeout(showAlert, 2000);
function showAlert() {
alert('Hi');
}
setTimeout(showAlert, 2000, "Hi", " programmer!");
function showAlert(parameter1, parameter2) {
alert(parameter1 + parameter2);
}
The alert box will show – Hi programmer!.
The below code will not show the alert box as there is clearTimeout() on the last line.
function showAlert(msg) {
alert('hi');
}
var timer=setTimeout(showAlert, 5000);
clearTimeout(timer);
This timer method calls a function or evaluates an expression at specified intervals. For example if you give the time as 4 seconds then the given function or expression will be called/evaluated in every 4 seconds.
Syntax:
setInterval(function, milliseconds, parameter1, parameter2, ...)
Parameter | Description |
---|---|
Function | Required. The function that will be executed |
Milliseconds | Required. The intervals (in milliseconds) on how often to execute the code |
paramerter1, paramerter2, … | Optional. Additional parameters to pass to the function |
setInterval(function(){ alert("Hi"); }, 2000);
Separate the function call from the syntax.
setInterval(showAlert, 2000);
function showAlert() {
alert('Hi');
}
setInterval(showAlert, 2000, "Hi", " programmer!");
function showAlert(parameter1, parameter2) {
alert(parameter1 + parameter2);
}
The alert box will show – Hi programmer! in every 2 seconds time.
The below code will not show the alert box as I have added the clearTimeout() on the last line.
function showAlert(msg) {
alert('hi');
}
var timer=setInterval(showAlert, 5000);
clearTimeout(timer);
Download the source codes:
The setTimeout & setInterval are very useful JavaScript function. We can also use them in our jQuery code and create amazing features like time clock, stop watch, image sliders and more.