Javascript Timing
The window object provides the execution of code at specified time intervals.These time intervals are called timing events.
Mainly two key methods are provided to use with JavaScript are:
- setTimeout(function, milliseconds)
- setInterval(function, milliseconds)
The setTimeout() Method:
window.setTimeout(function, milliseconds);
EXAMPLE:
<!DOCTYPE html> <html> <body> <p>Click "Try it". Wait 3 seconds, and the page will alert "Hello".</p> <button onclick="setTimeout(myFunction, 3000);">Try it</button> <script> function myFunction() { alert('Hello'); } </script> </body> </html>
OUTPUT:
The setInterval() Method:
window.setInterval(function, milliseconds);
EXAMPLE:
<!DOCTYPE html> <html> <body> <p>A script on this page starts this clock:</p> <p id="demo"></p> <script> var myVar = setInterval(myTimer, 1000); function myTimer() { var d = new Date(); document.getElementById("demo").innerHTML = d.toLocaleTimeString(); } </script> </body> </html>
OUTPUT:
A script on this page starts this clock: 9:18:24 PM