Timing events in JavaScript
Published: 2022-11-15 14:26:54


JavaScript enables webpages to respond to user activity and enact a dynamic update, all without requiring a page reload to trigger change I'm the UI.


Timing events in JavaScript is the process of executing a JavaScript code within a specified time interval, which is also called periodic execution. 

It is permitting a specific block of code to run after a given period, so code will not run until the set time has lapsed or expired.

It consists of two methods, namely the setInterval() method and the setTimeout() method.


These are [asynchronous](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function)/await functions meaning that the block of code will wait on the permitted time event.


### setTimeout
The `setTimeOut()` method sets a timer that executes a function once the time is expired.


 `Syntax`
```js
var TimeoutID = setTimeout(function(){
//codes
}, delay);
)
```

`function` - will be executed when timer expires.
`delay` - the time in milliseconds, the duration the timer should wait before executing `function`.

In this example there'll an alert of saying hello world after 3000 milliseconds.

>Note: 1000 milliseconds is equal to 1 second.
```js
      function myFunc() {
         alert("Hello World!");
      }
      
      var myTimeout = setTimeout(myFunc, 3000);
```


***Output***
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5352wn7ygndk13lrxidx.png)

If the `setTimeOut()` method is included in JavaScript. In that case, a `function` will not be executed until the time specified in the `setTimeout()` method has lapsed, and this method is useful because it permits a `function` that needs to be executed after a specified amount of time.


### Canceling a timeout 
The `clearTimeout()` cancels a timeout function specified in the `setTimeout()` `function`.
What you will have to do is specify the `timeout` you want to cancel or abort. 
It will be canceled when you press the button.
Example below.

```html
<body>
   <p id="msg"> Click this button before 5 seconds to stop the alert pop-up. </p>
   <button onclick="cancelTimeout()"> Cancel Timeout </button>

   <script>
      var myTimeout = setTimeout(function() {
         alert("Hello World!");
      }, 5000);
      
      function cancelTimeout() {
         clearTimeout(myTimeout);
         document.getElementById("msg").innerHTML = "<b>myTimeout</b> has been cancelled, the alert saying "hello world will not pop-up";
      }
   </script>
</body>
```

***Output***

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4n9qnn1accf6qc4v00jp.png)


### setInterval()
`setInterval()` method repeatedly (a continuous call) calls a `function`.
`Syntax`
```js
var intervalID = setInterval(function(){
//codes
}, delay);
)
```

`function` _ will be executed every `delay` milliseconds.
`delay` _ the time in milliseconds, the duration the timer should wait at every interval before executing `function`.

```html
<body>
   <p id="demo">10</p>

   <script>
      var initial = 10;
      //our initial is 10, at intervals our initial will be increasing by 10
      var myInterval = setInterval(function() {
         // adds 10 to initial
         initial += 10;
         document.getElementById("demo").innerHTML ='initial is increasing every 1 sec ='+  " " +initial;
      }, 1000);
   </script>
</body>
```
***Output***


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wbgclq9kr0uwf6jij580.png)

>Output after 5 sec

Suppose the `setInterval()` method is included in JavaScript. In that case, a `function` will not be executed until the time specified in the `setInterval()` method is lapsed, and this method is useful in JavaScript, which requires the execution of a `function` again and again.


### Stopping an interval

The `clearInterval()` cancels a interval `function` specified in the `setInterval()` `function`.
What you will have to do is specify when you want to cancel or abort. 
It will be canceled when you press the button.
Example below.
```html
<body>
   <p id="demo">10</p>
   <button onclick="stopInterval()"> Stop Interval </button>

   <script>
      var initial = 10;
      
      var myInterval = setInterval(function() {
         // adds 10 to initial
         initial += 10;
         document.getElementById("demo").innerHTML = initial;
      }, 1000);
      
      function stopInterval() {
         clearInterval(myInterval);
alert ("interval has been stopped!");
      }
   </script>
</body>
```
***Output***


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/za41t2w41hj54ck6i1vs.png)
>Interval was stopped by clicking on the button after 4sec.


###Summary
*Introduction to JavaScript timing events
*Running executing functions using the `setTimeout` method and `setInterval()` method.
*Cancelling or aborting functions using `clearTimeout()` and `clearInterval()`.

In this article we were able to walkthrough the basic part of timing events, learn about[`setTimeout()`](https://www.google.com/url?sa=t&source=web&rct=j&url=https://developer.mozilla.org/en-US/docs/Web/API/setTimeout&ved=2ahUKEwjRvZPj1rL7AhUZJkQIHSSxADMQFnoECAwQAQ&usg=AOvVaw2n5P9_so5RmXh3uRRl0pbf) and [`setInterval()`](https://www.google.com/url?sa=t&source=web&rct=j&url=https://developer.mozilla.org/en-US/docs/Web/API/setInterval&ved=2ahUKEwjRvZPj1rL7AhUZJkQIHSSxADMQFnoECA0QAQ&usg=AOvVaw09vkyBihnLRr4VUq1-QrVa).

Thanks for reading, I hope it was helpful.