
Timers in JavaScript function? Explain any disadvantages of using the timer as well.
What are timers in JavaScript used for?
A timer is used in JavaScript to execute a task or function at a specific time. The timer is essentially used to delay the execution of the programmer or to execute the JavaScript code at regular intervals. We can delay the execution of the code by using a timer.
The window object allows code to be executed at predefined time intervals. These time intervals are referred to as timing events.
The two most important JavaScript methods are:
setTimeout (function, milliseconds):
After a specified number of milliseconds, executes a function.
setInterval (function, milliseconds):
The setTimeout() and setInterval() methods both return a unique ID (a positive integer value known as the timer identifier) that identifies the timer created by these methods.
The setTimeout() function takes a single parameter, an ID, and continuously clears a setTimeout() timer associated with that ID.
What distinguishes setTimeout from setInterval?
using setTimeout (): We can run a function once after the timeout
With the help of setInterval, we can run a function repeatedly, starting after the interval and repeating continuously at that time.
A setTimeout() Example in Javascript:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Timing</h2>
<button onclick="stop = setTimeout(timer, 3000)">setTimeout </button>
<button onclick="clearTimeout(stop)"> click me to Stop </button>
<script>
function timer() {
alert("Successfull you set your time");
}
</script>
</body>
</html>Click the “setTimeout” button. Wait three seconds. The page will notify you that you have successfully set your time.
To prevent the first function from executing before the 3 seconds are up, click “click me to Stop.”
setInterval():
The timing event is represented by the setInterval() method.
A function that will be run every delay millisecond. The first execution occurs after milliseconds of delay.
A setInterval() Example in Javascript:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Timing</h2>
<p>A script on this page starts this clock:</p>
<script>
setInterval(myTimer, 10000);
function myTimer() {
alert(new Date().toLocaleTimeString()) ;
}
</script>
</body>
</html>setTimeout():
is an asynchronous function, which means it will not pause the execution of other functions on the functions stack. JavaScript is a flexible single-threaded, non-blocking, asynchronous, concurrent programming language. setTimeout() is a common JavaScript function. It starts a timer (a countdown in milliseconds) for the execution of a call back function, then calls the function when the timer expires.
Timers are perfectly acceptable. There will be a performance issue only if you do not keep the interval ids and run multiple intervals at the same time (especially when the delay is very less). To avoid this, clear the current interval before starting a new one. This ensures that only the required interval is active.