Difference between settimeout and setinterval in javascript

Hi Frineds,

Most of people are confused in javascript timer functions. I got many questions on this.

So today I am going to describe the differences between setInterval and setTimeout, which are both time interval based code execution methods of the JavaScript language.

How does the JavaScript function setTimeout work?
setTimeout() : It is used to execute a certain function at the end of given time.
below is the syntax for this function:

var timerVariable = setTimeout(func|code, delay)

func|code
    Function variable or the string of code to execute.
delay
    The delay in milliseconds, 1000 milliseconds = 1 second.

The execution will be performed once after the specified delay.

For example, the code below fires an alert after three seconds:

function functionName() { 
  alert('JavaScript setTimeout example')
}
setTimeout(functionName, 3000)

How does the JavaScript function setInterval work?
setInterval() : It repeats itself at regular time that is passed to this function.
below is the syntax for this function:

var timerVariable = setInterval(func|code, delay)

func|code
    Function variable or the string of code to execute.
delay
    The delay in milliseconds, 1000 milliseconds = 1 second.

The execution will be performed continuously every time the number of delay.

For example, the code below fires an alert on every three seconds:

function functionName() { 
  alert('JavaScript setInterval example')
}
setInterval(functionName, 3000)

Now the question is; how can we stop the execution which was started by the setTimeout and setInterval functions.

For this, we can use clearTimeout() and clearInterval() functions.

below is the syntax for this functions:

clearTimeout(timerVariable) AND
clearInterval(timerVariable)

Hope you enjoyed this article !!!

Leave a Reply

Your email address will not be published. Required fields are marked *


You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>