JavaScript timer

In JavaScript, a timer is implemented to run a task or a function at a specific time. Essentially, timers are utilized to postpone the execution of a program or to run JavaScript code at consistent time intervals. By employing timers, we can defer the execution of code, ensuring it does not finish executing simultaneously when an event occurs or a page is loaded.

An excellent illustration of a timer is seen in advertising banners on websites, where they switch every 2-3 seconds. These promotional banners are updated periodically on platforms such as Amazon by setting a specific time interval for their rotation. This section will guide you through the process of crafting a timer.

JavaScript provides developers with two timer functions: setInterval and setTimeout. These functions are useful for introducing delays in code execution and for carrying out multiple operations in a repetitive manner. In the following sections, we will delve into a comprehensive exploration of both timer functions along with illustrative examples.

Examples

Presented here are a few instances of JavaScript timer implemented with the following functions.

setTimeout

The setTimeout method is used to postpone the execution of code. It requires two arguments: a custom function defined by the user and a time parameter that specifies the delay duration. The time parameter is measured in milliseconds (1 second = 1000 milliseconds) and is not mandatory to provide.

The basic syntax of setTimeout is:

Example

setTimeout(function, milliseconds)

To introduce a delay of 3 seconds before displaying a message on the web page, the setTimeout function can be employed. This function allows the message to appear on the screen after a 3-second pause following the execution of the code. Below is an example demonstrating this concept:

Execution of code after a delay

Example

<html>

<body>

<script>

function delayFunction() {

    //display the message on web after 3 seconds on calling delayFunction

    document.write('<h3> Welcome to our tutorial <h3>'); 

}

</script>

<h4> Example of delay the execution of function <h4> 



<!?button for calling of user-defined delayFunction having 3 seconds of delay -->

<button onclick = "setTimeout(delayFunction, 3000)"> Click Here </button>



</body>

</html>

Output

The code above will run in two stages. Initially, the HTML segment of the code will be executed. Upon clicking the "Click Here" button, the remaining JavaScript code will run after a delay of 3 seconds. The resulting output can be observed below:

Upon clicking the "Click Here" button, the subsequent code will be executed with a delay of 3 seconds. Following this delay, a message saying "Welcome to our tutorial" will appear on the webpage after 3 seconds, equivalent to 3000 milliseconds.

setInterval

The setInterval function operates in a comparable manner to the setTimeout function by running a designated function at regular intervals. Essentially, it allows a function to run repeatedly at a set time interval specified by the user. For instance, it can be used to continuously update and display the current time every five seconds.

The basic syntax of setInterval is:

Example

setInterval(function, milliseconds)

Just like the setTimeout function, this function also takes two arguments - a function defined by the user and a time delay parameter specifying when to execute the function. The time delay parameter represents the duration in milliseconds (1 second = 1000 milliseconds) and can be omitted. Check out the following example code to observe the functionality of this method:

Execution of code at a regular interval

Example

<html>

<body>

<script>

function waitAndshow() {

       //define a date and time variable

       var systemdate = new Date();

    

       //display the updated time after every 4 seconds

       document.getElementById("clock").innerHTML = systemdate.toLocaleTimeString();

}



      //define time interval and call user-defined waitAndshow function

      setInterval(waitAndshow, 4000);

</script>



<h3> Updated time will show in every 4 seconds </h3>

<h3> The current time on your computer is: <br>

<span id="clock"></span> </h3>



</body>

</html>

Output

Upon running the provided code, the output will consist of a basic HTML statement that does not include any timestamp information, as illustrated below:

Following a 4-second delay, the JavaScript function will be invoked to initiate the display of the current time. Subsequently, the function will update and show the system time every 4 seconds in a repetitive manner.

Example

Here's another illustration utilizing the setInterval function to showcase a message string at intervals of 4 seconds consistently.

Example

<html>

<body>

<script>

function waitAndshow() {

    //display the message on web on calling delayFunction

    document.write('<h3> Welcome to our tutorial <h3>'); 

}

</script>

<h3> A string will show in every 4 seconds </h3>

<!-- call user-defined delayFunction after 4 seconds -->

<button onclick = "setInterval(waitAndshow, 4000)"> Click Here </button>



</body>

</html>

Output

Upon running the provided code, a notification containing a clickable button will be displayed in the web browser. To proceed further and observe the subsequent actions, simply click on this button.

Upon selecting the Click Here button, the function waitAndshow will initiate the continuous display of the message "Welcome to our tutorial" on the webpage at intervals of 4 seconds.

In previous sections, we discussed how to initiate timers and establish time intervals. Occasionally, there arises a necessity to terminate these timers. JavaScript provides a built-in method to cancel timers, as outlined below:

Cancel or Stop the timer

In JavaScript, there are two functions available for canceling timers and pausing code execution: clearTimeout and clearInterval. When setTimeout and setInterval are called, they each provide a distinct ID as a return value. These IDs serve as references for clearTimeout and clearInterval to respectively cancel the timer and cease the code execution prematurely. Both clearTimeout and clearInterval accept a single argument, which is the ID of the timer to be cleared.

Example

In this instance, we will demonstrate the utilization of clearTimeout to eliminate the timer established by the setTimeout function. Observe how clearInterval functions in conjunction with setInterval in the provided example.

Disable the regular interval

Example

<html>

<body>

<script>

function waitAndshow() {

  //define a date and time variable

  var systemdate = new Date();

    

  //display the updated time after every 4 seconds

  document.getElementById("clock").innerHTML = systemdate.toLocaleTimeString();

}



 //function to disable the time interval

function stopClock() {

    clearInterval(intervalID);

}



//define time interval and call user-defined waitAndshow function

var intervalID = setInterval(waitAndshow, 3000);

</script>

 

<p>Current system time: <span id="clock"> </span> </p>



<!-- button to stop showing time in a regular interval -->

<button onclick = "stopClock();" > Stop Clock </button>

</body>

</html>

Output

Upon running the provided code, the webpage will display the current system time at regular 3-second intervals. A button on the page allows users to deactivate this timer functionality.

The timer will refresh and display the current time every three seconds. Pressing the Stop Clock button will deactivate the timer and prevent it from updating and showing the current time.

Input Required

This code uses input(). Please provide values below: