Sunday, May 10, 2020

JavaScript setTimeout and setInterval

JavaScript Timer Events


setTimeout and setInterval


There are some JavaScript native functions (also known as timers) that enable us to delay the execution of arbitrary instructions. We may run a function at a certain time later. These methods can be used for scheduling the tasks in the future.


JavaScript provides two methods for this 

  • setTimeout
  • setInterval

setTimeout() method


The setTimeout() method is used if we want our function to be executed after a specified number of milliseconds from when the setTimeout() method was called.

setTimeout ( expression, timeout );

The expression is the code to be executed after timeout milliseconds. The setTimeout() method also returns a timeout id that can is used with clearTimeout(timeoutid) method. The setTimeout() method can be used to clear the timeout. 

For example

<html>   
<body> 
<h2> Timer Demo</h2> 
<button onclick='runTimer()'>Start</button> 
<script>
function runTimer()
{
setTimeout('alert("Timer completed")',5000);
}
</script>  
</body>  
</html>  

Once the button start is clicked, the alert box will be displayed after 5000 milliseconds. This will not block other code to execute the timer will execute in the background.


setInterval() method


The setInterval() method is very much like the setTimeout() method except, it keeps executing the expression after a specified amount of time repeatedly. This method returns a timerid that can be used with clearInterval() method.

setInterval ( expression, interval);
The timer can be cleared using the clearInterval(timerid) method.

For example,

<html>   
<body> 
<h2> Timer Demo</h2> 
<button onclick='runTimer()'>Start</button> 
<button onclick='stopTimer()'>Stop</button> 
<script>
var id=0;
function runTimer()
{
id=setInterval('alert("Repeated Timer")',5000);
}
function stopTimer()
{
clearInterval(id);
}
</script>  
</body>  
</html>