Saturday, February 25, 2023

Timing Events in JavaScript: setTimeout and setInterval

Timing Events in JavaScript: setTimeout and setInterval

JavaScript timing events are used to run code at a specific time or after a specific period of time. These events are frequently used in web development for animations, slide presentations, and other dynamic features that call for updates or changes over time.

The window object, which offers the setTimeout and setInterval methods for scheduling events, is in charge of controlling JavaScript timing events. In JavaScript, the unit of time measurement for timing events is milliseconds, which provides a good balance between precision and practicality. 1000 milliseconds represents one second, 2000 milliseconds represents two seconds, and so on.

Delayed Events With the setTimeout Function

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

setTimeout(function, milliseconds);

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

The first parameter is a function to be executed. The second parameter specifies how many milliseconds to wait before execution. If for example, you want a message saying "Hey there" to pop up on the screen after three seconds, this is how the code would look: 

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 function is used to execute a piece of code repeatedly at predetermined intervals. This function's syntax is as follows:

setInterval(function, milliseconds);

The first parameter is a function to be executed. The second parameter specifies the interval between each execution. Let's build a simple digital clock that displays the current time to demonstrate this. The clock executes the function digitalClock every one second, just like how a digital watch works.

Clearing Timing Events

We might at some point want to stop a function from running after it has ran for a few times or a specified period 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 the setTimeout() function. The setTimeout() function returns a timing id. You can use this id to clear the timeout later with 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 the Start button, it waits for 3 seconds before the "Hey there" message is alerted. If you happen to click the End button before that 3 seconds is up, it stops the function from being executed.

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

The clocks starts working once the page is loaded but when you click the Stop time button, it stops. 

Importance of Clearing the Timing Event Functions

When using timing events in JavaScript, it's crucial 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 required, you should remove the reference from memory to avoid memory use from increasing. Performance problems may eventually result from this, 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 navigates away from the page, the interval will keep firing even when the user is no longer viewing the page. 

By calling clearTimeout() or clearInterval(), you can cancel the outstanding timer and prevent these issues from occurring. This helps to avoid memory leaks and unexpected behavior while ensuring that your code is effective and predictable.

Example Project Combining Both Timing Events

Here's a little project to demonstrates the two main JavaScript timing events in a more advanced functionality. This is a simple web page that uses setInterval() to display a random number every second and setTimeout() to stop the display after 20 seconds.

Here are a few ideas for other little learning projects you could try to sharpen your skills with the interval and timeout functions:

  • countdown timer
  • random quote generator
  • slideshow animation
  • JavaScript quiz game with timer

Conclusion

Timing events in JavaScript are a useful tool for web developers, as it enables them to create dynamic and interactive web pages. The setTimeOut() and setInterval() functions offer a simple approach for scheduling code execution at a particular time or interval. These functions can be used to make a slide show, 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.


No comments:

Post a Comment