The window object enables code execution at specified time intervals, known as timing events.
The two primary methods used in JavaScript are:
setTimeout(function, milliseconds): Executes a function after a specified delay in milliseconds.
setInterval(function, milliseconds): Similar to setTimeout(), but repeats the function execution at regular intervals.
Both setTimeout() and setInterval() are methods of the HTML DOM’s Window object. |
| window.setTimeout(function, milliseconds); |
The setTimeout() method can be used without the window prefix.
The first parameter is the function to execute, and the second parameter specifies the delay in milliseconds before execution.
Click a button, wait for 3 seconds, and then the page will display an alert saying “Hello”.
| <button onclick=”setTimeout(myFunction, 3000)”>Try it</button> <script> function myFunction() { alert(‘Hello’); } </script> |