Timing events in JavaScript: setTimeout and setInterval


JavaScript timing events are used to execute code at a specific time or after a specific amount of time. These events are often used in web development for animations, slideshows, and other dynamic features that require updates or changes over time.

THE window object, which offers the setTimeout AND setInterval methods for scheduling events, is responsible for checking JavaScript timing events. In JavaScript, the unit of time for timing events is milliseconds, which provides a good balance between accuracy and convenience. 1000 milliseconds represents one second, 2000 milliseconds represents two seconds, and so on.

Delayed events with the setTimeout Function

THE setTimeout The function is used to execute a piece of code after a predetermined amount of time. The syntax of this function is as follows:

setTimeout(function, milliseconds);

This executes a function, after waiting a specified number of milliseconds.

The first parameter is a function to execute. The second parameter specifies how many milliseconds to wait before executing. For example, if you want a message that says “Hey there” to appear on the screen after three seconds, this is what the code would look like:

1
<button onclick="setTimeout(timingFunction, 3000)">Click Me!</button>
2

3
function timingFunction() {
4
    alert('Hey there');
5
}
6


Repeated events with the setInterval Function

THE setInterval The function is used to repeatedly execute a piece of code at predetermined intervals. The syntax of this function is as follows:

setInterval(function, milliseconds);

The first parameter is a function to execute. The second parameter specifies the interval between each run. Let’s build a simple digital clock that displays the current time to demonstrate this. The watch performs the function digitalClock every second, just like a digital clock works.

Deletion of timing events

We may at some point want to stop executing a function after it has run for a few times or for a specified amount of time. To stop timed execution, prefix clear to the timing event function you are working with.

THE clearTimeout() function is used to stop the execution of a function specified in setTimeout() function. THE setTimeout() the function returns a timing id. You can use this ID to cancel the timeout later clearTimeout().

1
<button onclick="timingID = setTimeout(timingFunction, 3000)">Start</button>
2
<button onclick="clearTimeout(timingID)">End</button>
3

4
function timingFunction() {
5
  alert("Hey there");
6
}

If you click on the Start button, waits 3 seconds before the “Hey there” is notified. If you happen to click the END button before 3 seconds have elapsed, stops the execution of the function.

Similarly, the clearInterval() The function is used to stop the execution of a specified function in setInterval() function. Just like for setTimeout()use the id of the timer returned by setInterval() function as an argument. To demonstrate this, we’ll add a stop button to the digital clock example above.

The clocks start running once the page loads, but when you click Stop time button, it stops.

Importance of clearing timing event functions

When using timing events in JavaScript, it is vital to keep in mind that the events must be cleared using the clearTimeout() OR clearInterval() function for the following reasons:

To prevent memory leaks

A reference to the function you want to run is stored in memory when you set a timeout or interval in JavaScript. When a timeout or interval is no longer needed, the reference should be removed from memory to prevent memory usage from increasing. Performance issues could eventually ensue, especially if you’re dealing with a lot of data.

To prevent unexpected code behavior

If you have an interval that refreshes the UI every second but doesn’t clear it when the user leaves the page, the interval will continue to fire even when the user is no longer viewing the page.

On call clearTimeout() OR clearInterval(), you can cancel the pending timer and prevent these problems from happening. This helps prevent memory leaks and unexpected behavior while ensuring that your code is effective and predictable.

Example project that combines both timing events

Here’s a little project to demonstrate the two main JavaScript timing events in more advanced functionality. This is a simple web page using setInterval() to display a random number every second e setTimeout() to stop viewing after 20 seconds.

Here are some ideas for other small learning projects you could try to hone your skills with interval and timeout functions:

  • countdown
  • random quote generator
  • presentation animation
  • JavaScript trivia game with timer

Conclusion

Timing events in JavaScript are a useful tool for web developers, as it allows them to create dynamic and interactive web pages. THE setTimeOut() AND setInterval() Functions offer a simple approach to scheduling code execution at a particular time or interval. These functions can be used to create a presentation, animations and other interactive elements that need to be updated or changed over time on a web page.

Post thumbnail generated with OpenAI’s DALL-E 2.



Source link

By LocalBizWebsiteDesign

Leave a Reply

Your email address will not be published. Required fields are marked *