pwshub.com

JavaScript Timer – How to Set a Timer Function in JS

JavaScript Timer – How to Set a Timer Function in JS

In Javascript, the timer function prevents your code from running everything at once when an event triggers or the page loads. This gives you more control over the timing of your program's actions and can enhance the user experience by creating smoother interactions or animations.

In this tutorial, you'll learn how to use the set timer functions.

There are various ways of setting a timer function, such as the setTimeout, setInterval, clearTimeout, and setImmediate functions. You'll learn about each of them in this article.

How to Use setTimeout and setInterval

The setTimeout function executes an expression after a specified delay in milliseconds while the setInterval function executes an expression after a specified interval in milliseconds.

You can use the setTimeout() function when you want to execute code block with a specific delay, but just once.

The setTimeout function is denoted by setTimeout(). Here's an example of how you can use it:

// Execute a function after 3 seconds
⁠ const timeoutId = setTimeout(() => {
    console.log('Timeout executed after 3 seconds');
}, 3000);

The above code block shows how to use the setTimeout syntax to execute a function after 3 seconds. The name of the variable is timeoutId which stores the execution of the setTimeout. The time set is 3000 milliseconds (or 3 seconds).

You can use the setInterval() function when you want to execute a code block repeatedly but at specific intervals – for instance, when animating elements.

The setInterval function is denoted by setInterval(). Here's how you can use it:

// Execute a function every 1 second
const intervalId = setInterval(() => {
    console.log('Interval executed every 1 second');
}, 1000);

The above code block shows how to use the setInterval syntax to execute a function after 1 second. The name of the variable is intervalId which stores the execution of the setInterval. The time is set to 1000 milliseconds (1 second).

How to Use clearTimeout and clearInterval

The clearTimeout function cancels a timeout previously scheduled with  the setTimeout function. clearInterval cancels an interval previously set with ⁠setInterval .

The clearTimeout function is denoted by clearTimeout();. It accepts an argument that stores the setTimeout function.

Here's an example of how it works:

const timeoutId = setTimeout(() => {
    console.log('Timeout executed after 3 seconds');
}, 3000);
clearTimeout(timeoutId);
console.log('Timeout cleared');

The clearTimeout function takes the variable name timeoutID which stores the setTimeout function and clears the function.

The clearInterval function is denoted by clearInterval();. It accepts an argument that stores the setInterval function under the block of the setTimeout function.

Here's an example of how it works:

const intervalId = setInterval(() => {
    console.log('Interval executed every 1 second');
}, 1000);
setTimeout(() => {
    clearInterval(intervalId);
    console.log('Interval cleared. Function will no longer execute.');
}, 5000);

In the above code block, the setTimeout function is introduced. The clearInterval function is passed into the code block, the argument intervalId is passed, and then the function is executed.

Another timer function is setImmediate which executes a function asynchronously as soon as possible after the current code block finishes executing. But it’s not universally supported across all browsers, so it’s rarely used.

Wrapping Up

It's important to know how to use JavaScript timer functions and when to apply them to your code. And remember that the timer is set to milliseconds, so whatever number you use, divide it by 1000 to determine how many seconds it is.

If you have any questions, you can reach out to me on Twitter 💙.

Source: freecodecamp.org

Related stories
3 weeks ago - Tauri is an excellent toolkit for building lightweight, secure, and cross-platform desktop applications. Learn more in this guide. The post Tauri adoption guide: Overview, examples, and alternatives appeared first on LogRocket Blog.
3 days ago - In this tutorial, you will learn how to build a custom countdown timer to track events using React.js. A countdown timer is a simple way to measure the time until an event happens. It counts down that time in reverse – like 5, 4, 3, 2, 1....
3 days ago - How should a website look? What size should the buttons be? What layout should you use? Do your users need an OTP to reset their passwords? These are all questions that proper user interface and user experience (UI/UX) design answer....
1 week ago - The Back Story A few years ago, I was introduced to React and immediately fell in love with its component-based, state-driven approach to building web applications. But as I delved deeper into its ecosystem, I encountered not just React,...
1 month ago - Building projects is a great way to practice and improve your web development skills. And that's what we'll do in this in-depth tutorial: build a practical project using HTML, CSS, and JavaScript. If you often find yourself wondering...
Other stories
2 hours ago - Fixes 41 bugs (addressing 595 👍). node:http2 server and gRPC server support, ca and cafile support in bun install, Bun.inspect.table, bun build --drop, iterable SQLite queries, iterator helpers, Promise.try, Buffer.copyBytesFrom, and...
7 hours ago - This guide provides a foundational understanding of Redux and why you should use it for state management in a React app. The post Understanding Redux: A tutorial with examples appeared first on LogRocket Blog.
9 hours ago - Discover some of the best Node.js web scraping libraries, including Axios and Superagent, and techniques for how to use them. The post The best Node.js web scrapers for your use case appeared first on LogRocket Blog.
12 hours ago - Infinite runner games have been a favorite for gamers and developers alike due to their fast-paced action and replayability. These games often feature engaging mechanics like endless levels, smooth character movement, and dynamic...
14 hours ago - Yesterday, Elizabeth Siegle, a developer advocate for CLoudflare, showed off a really freaking cool demo making use of Cloudflare's Workers AI support. Her demo made use of WNBA stats to create a beautiful dashboard that's then enhanced...