In Javascript we can execute some code at specific time intervals. These are called timing events.
There are two methods that are used:
1.setInterval()
2.setTimeout()
setInterval() Method : The setInterval() method executes the function at a specified number of milliseconds and it will continue to execute the function again at that specific time interval.
Syntax:
window.setInterval("javascript function", milliseconds);
Example:
<!DOCTYPE html>
<html>
<body>
<button onclick="setInterval(function(){alert('Hii')},3000);">Click here</button>
</body>
</html>
In the above example when we click on the button, It will alert the message after every 3 seconds.
clearInterval() : This method is used to stop the further executions in the setInterval() method.
Syntax:
window.clearInterval(intervalVariable)
setTimeout() Method : This method will execute the function after a specified time interval. The first parameter in this is a function to execute and the second parameter is the time in miliseconds.
Syntax:
window.setTimeout("javascript function", milliseconds);
Example:
<!DOCTYPE html>
<html>
<body>
<button onclick="setTimeout(function(){alert('Hello')},5000);">Click here</button>
</body>
</html>
This will show the alert message after 5 seconds on clicking the button.
0 Comment(s)