The best example of the timer is advertisement banners on websites, which change after every 2-3 seconds. These advertising banners are changed at a regular interval on the websites like Amazon. We set a time interval to change them. In this chapter, we will show you how to create a timer.
The setTimeout() function helps the users to delay the execution of code. The setTimeout() method accepts two parameters in which one is a user-defined function, and another is the time parameter to delay the execution. The time parameter holds the time in milliseconds (1 second = 1000 milliseconds), which is optional to pass.
The basic syntax of setTimeout() is:
We will use the setTimeout() function to delay the printing of message for 3 seconds. The message will display on the web after 3 seconds of code execution rather than immediately. Now, let's look at the code below to see how it works:
Execution of code after a delayTest it Now
On clicking the Click Here button, the remaining code will execute after 3 seconds. A message Welcome to javaTpoint will display on the web after 3 seconds (3000 milliseconds).
The setInterval method is a bit similar to the setTimeout() function. It executes the specified function repeatedly after a time interval. Or we can simply say that a function is executed repeatedly after a specific amount of time provided by the user in this function. For example - Display updated time in every five seconds.
The basic syntax of setInterval() is:
Similar to setTimeout() method, it also accepts two parameters in which one is a user-defined function, and another is a time-interval parameter to wait before executing the function. The time-interval parameter holds the amount of time in milliseconds (1 second = 1000 milliseconds), which is optional to pass. Now, see the code below how this function works:
Execution of code at a regular intervalTest it Now
On executing the above code, the response will be a simple HTML statement without any time string like below output:
One more example of setInterval() methods for displaying a message string after every 4 seconds continuously.Test it Now
On executing the above code, a message with a button will show on the browser. Click on this button to process more and see what happens next.
By clicking on this Click Here button, the waitAndshow() will start printing the message Welcome to Javatpoint repeatedly on the web in every 4 seconds.
Cancel or Stop the timer
In this example, we will use clearTimeout() to clear the timer set by with setTimeout() function. Look at the example how clearInterval() work with setInterval().
Disable the regular intervalTest it Now
By executing the above code, the current system time will start showing on the web with 3 seconds of regular interval. This page also has a button to disable this timer.
The timer will show the updated time after every three seconds. If you click on this Stop Clock button, the timer will be disabled and stop showing the updated time.