Home    Articles

 

How to use 'setInterval()' and "setTimeout()"

 

These two javascript functions , setTimeout() si setInterval() are often used.
These functions are used in motion effects or when the programmer needs to do something at some point.
What exactly setTimeout() and setInterval() do? These can decide the exection of a function at a certain time interval.
The sintax to call these two javascript functions is:
setTimeout(“some_function()”, time) – where some_function() is your function that will do something, anything you want.
This function will call the function after some time, the time can be set as 1000.
That means 1 sec or 1000 ms.

setInterval((“some_function()”, time) – where some_function() is your function that will do something, anything you want.
This function will call repeatedly the some_function() function after a period of time.
The time param is the same.

conclusion: these functions may look simillar, but there is a difference between them. setInterval will call a function repeatedly and setTimeout will call the functione once.
Let’s have some examples:
Using setTimeout()

Here the number (nr) will be added
<script type="text/javascript">// <![CDATA[
var nr = 0;//this will be incremented
    function some_function()
    {
        nr++;         // incrementing
        document.getElementById('display_div').innerHTML = nr;  //this will add the "nr" in div with id "display_div"
    }
// ]]></script>setTimeout("some_function()", 3000);

And using setInterval()

Here the number (nr) will be added
<script type="text/javascript">// <![CDATA[
var nr = 0;//this will be incremented
    function some_function()
    {
        nr++;         // incrementing
        document.getElementById('display_div').innerHTML = nr;  //this will add the "nr" in div with id "display_div"
    }
// ]]></script>setInterval("some_function()", 3000);
by