setTimeout: This method is used to delay
execution of some code. It is used to execute a certain function or jQuery code
at the end of given time. It takes the time in milliseconds.
Syntax
of setTimeout:
setTimeout(function () {
// Do something after given time
}, Time in millisecond);
For example
you want to hide a div, 5 seconds after the page loads, then you can do it
as:
HTML:
<div id="exampleDiv">This is example div for set time out </div>
JQuery:
setTimeout(function () {
$('#exampleDiv').hide();
}, 5000);
|
setInterval: This method repeats itself at
regular time that is passed to this function, we can compare this method to an
alarm clock that strikes repeatedly after a particular interval. It also takes the time in milliseconds.
Syntax
of setInterval:
setInterval(function () {
// Do something per given time
}, Time in millisecond);
For example
we want to multiply a number by 2, every second:
HTML:
JQuery:
setInterval(function () {
$('#testInterval').text(parseInt($('#testInterval').text(),
10) * 2);
}, 1000);
Default value in div is ‘1’ which is
string so we’ll convert it into integer value with the help of parseInt()
method, and it’ll be multiplied by 2 every second, Check live demo on jsfiddle.
|
Comments
Post a Comment