1

JavaScript 101: All About Timers

 1 year ago
source link: https://blog.bitsrc.io/javascript-101-all-about-timers-cec07db55b86
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

JavaScript 101: All About Timers

Timers can be powerful tools if you know how to use them

1*XGVFOKigIN2fnvodAIPvgQ.jpeg

JavaScript timers are great tools for achieving recurrent behavior or even triggering delayed actions.

Whatever time-based logic you have, timers are the answer to your questions.

But if you don’t fully understand how they work, then you’ll be hitting your head against a JavaScript-made wall.

Let’s take a look at what timers we have available and how they work.

The main thing to remember about timers

Before we get into the nitty-gritty details of timers, there are a couple of very important things to remember about them.

They’re not exactly accurate

Timers either trigger an action after a certain number of seconds or repeat an action every time the specified timeout is over.

But while your expectation might be that they are accurate to the second, the reality is that they’re not.

The specs for these timers state that they will use the time parameter (as in, the number of seconds you specify) as a minimum waiting time. But they can certainly take longer if there are other tasks that need to finish first.

This is only a problem if your logic depends on exact time measurements, like having a clock counting seconds with a setInterval callback.

As long as we keep that in mind, then we’re safe using timers.

They’re asynchronous functions

That means they won’t stop the program flow until they’re done. Even if you specify 0 as a timeout value, their behavior will still be asynchronous.

That means these functions will add the reference to the function you want to trigger into the event loop, so even if you specify a 0 on the timeout value, the reference will be queued up after everything that comes next.

Understanding setTimeout

The setTimeout function is probably the easiest one to understand, since the main objective is to trigger a function after a number of seconds.

This function receives:

  • A function reference to execute. This is the code that will be triggered once the time is up.
  • The number of seconds before the function gets executed.
  • All other parameters are then passed to the executed function in the same order.

So the following code will print “Hello World” after 3 seconds:

This works because the console.log function concatenates all parameters received and outputs a string.

But what happens if instead you have something like this:

While line 14 will work, line 16 won’t. This is because the execution context of the called function changes. In fact, it changes to the global scope. In Node that would be global , on the browser h, it would be window .

In both cases, the function’s this changes, so when line 16 gets executed, the reference this.c no longer exists.

So to solve this problem, you can simply create a wrapper function like this:

Notice the wrapper anonymous function I added on line 16, now when the anonymous function gets called with the two parameters. Inside it, we directly call c.log with the call method (it’s a method that every function has). We use the call method because we’re passing the arguments received by the anonymous function directly into the log method. We can’t do this without using call because we’re going with a dynamic approach.

If we had hardcoded the parameters on the anonymous function, we could be calling the log method directly, like this:

Remember that setTimeout is a special type of async function, so whatever code you write after it, will execute before the function is triggered, no matter what:

The output from that code is the following:

1*CRuR_1pABR2SPb81H1pKEA.png

Notice how lines 3 and 9 are the last to be executed, even when line 9 has a timeout of 0.

One more thing!

Before we leave setTimeout alone, what happens if you set the timeout value and then realize you have to stop it? You can kill the timer before it gets to be executed if you save the returned value (the timer ID).

That value can then be used with the clearTimeout function to stop the timer before the timeout gets triggered.

Let’s edit the code from before, but instead, now I’ll clear the first timeout:

With the above code, we’re killing the first timer before it executes the code, so the string Third! (1) won’t be printed out.

What happens though, if instead of killing it, you need it to repeat itself every few seconds? That’s where setTimeout falls short, and we can use its brother: setInternval

Understanding setInterval

The setInterval function is very similar to setTimeout , but instead of triggering the function only once, it triggers the function until otherwise stopped.

The signature of this function is exactly the same as for the setInterval one, and the explanation for all the parameters is the same as well.

That can also be said for the limitations around the context of this inside the triggered function. And the solution for it is the same: a wrapper function.

The above code will start a loop that triggers every 1 second, and when it triggers, a random name will be picked and the string “Hello <name>” will be printed.

Not only that, but we’re also setting a timeout of 4 seconds that will end the infinite loop by calling the clearTimeout function. Granted, you also have the clearInterval function but since they work with the same pool of timers, you can use them interchangeably.

Timers are fantastic tools to generate repeated or delayed behavior, and they’re useful especially when you have to interact with other services under certain time-based conditions.

Both, timeouts and intervals can be stopped before they’re triggered using the clear* functions as long as you kept the returned ID from calling the function.

Do you have any more questions about timers in JavaScript? Leave them in the comments and I’ll do my best to answer them!

Build Apps with reusable components, just like Lego

1*mutURvkHDCCgCzhHe-lC5Q.png

Bit’s open-source tool help 250,000+ devs to build apps with components.

Turn any UI, feature, or page into a reusable component — and share it across your applications. It’s easier to collaborate and build faster.

Learn more

Split apps into components to make app development easier, and enjoy the best experience for the workflows you want:

Micro-Frontends

Design System

Code-Sharing and reuse

Monorepo


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK