setInterval(), clearInterval(), setTimeout(), clearTimeout() function in javascript
Difference between setInterval() and setTimeout(), Difference between clearInterval() and clearTimeout()
What is setInterval()?
It is a function which calls a function or executes code snippets after a repeating time.
To break the continuation you have to define clearInterval(). setInterval() returns a interval ID, which identifies interval uniquely.
Syntax
setInterval(functionname, delay, argument1, argument2....)
function functionname(a,b){
// Your code
//parameters are optional
console.log(a);
console.log(b);
}
parameters
functionname
A defined function is first executed at delay time completion and after again completion of delay and so on.
delay(optional)
It is time defined by the programmer in milliseconds. If not specified, its default value is 0.
argument1, argument2..(optional)
It is additional arguments if required.
Return Value
It returns a value IntervalID, which is a non-zero value that identifies the timer created by setInterval().
Examples
we will take a heading tag and we will change its text color green to red by code after 1 second.
output:
After every one second text color changes green to red and red to green.
clearInterval()
It is used to break continuition of setInterval(). It cancels the time provided function setInterval().
Syntax
clearInterval(IntervalID);
Parameters
IntervalID is an identifier in which setInterval() is defined. In the above example IntervalID is changecolor.
Examples
If we want to clear settimeinterval in the above example. we have to code this. After single execution setinterval will become stop.
setTimeout()
This function executes the code only once when time expires. It is different from setInterval() because it executes only single time.
syntax
setTimeout(functionname, delay, parameter1, parameter2...)
functionname
A defined function is first executed at delay time completion and after again completion of delay and so on.
delay(optional)
It is time defined by the programmer in milliseconds. If not specified, its default value is 0.
argument1, argument2..(optional)
It is additional arguments if required.
Return Value
This function returns a positive integer after the call. This value is used by clearTimeout().
Example
Here we are defining three function in different delay.
After time expire..it will print
clearTimeout()
This method is used to cancel timeout previously established by calling setTimeout().
syntax
clearTimeout(TimeoutID);
parameter
TimeoutID is an identifier in which Timeout() is defined.
Return Value
None.
Example
Timeoutid will not print any output in console.