30 Days Of JavaScript

Day 17: Events

Lesson 3: setTimeout

setTimeout isn't really an event, but it let's you set stuff up to happen in the future that looks like an event from our perspective. Since I didn't get to cover this super useful function in the Day 11 (Async) like every other course would with a detailed (and boring) explanation of Promise creation, I will do it here instead.

It looks like this.

1setTimeout(() => {
2  // your code here
3}, 1000);

setTimeout is a function, that takes a function as it's first argument () => {} and a time delay in milliseconds for when to execute it.

Add this to your doneButton.onclick function

1setTimeout(() => {
2  alert(`Awesome, you finished a task`);
3}, 500);

Now click done, notice the small delay before the alert pops up? Change the 500 to 3000. Click done again and you'll really feel the delay.

Let's expand this a bit. Each time we click a task right now an alert pops, that's a bit annoying.

Let's make it so that no matter how many things get done we only show one alert at the end.

We can do this by still creating the timeout when the user clicks done but then, if they click done again in less than say 2 seconds we cancel the first one and create another with a delay of 2 seconds.

We can do that by saving the timeout id that setTimeout turns and then using cancelTimeout() before creating the next timeout. Let's see it.

Add this right before your todos.forEach() line:

1let currentTimeout;

This is the temporary storage for our running timeout.

Then change the onclick handler to this:

1doneButton.onclick = (e) => {
2  e.target.parentNode.remove();
4  clearTimeout(currentTimeout);
6  currentTimeout = setTimeout(() => {
7    alert(`Awesome work`);
8  }, 2000);

We remove the item, we then clear any timeout that maybe running (it doesn't matter if one isn't running when we call clearTimeout) and then we create our timeout just as before.

Give it a try, click done on all of them quickly and you'll see we still just get one alert. If you comment out the line clearTimeout(currentTimeout); and do it again you'll see we get three.


Go Pro?

If you upgraded to pro, sign in here

  • About
  • Blog
  • Privacy
Looking to email me? You can get me on my first name at allthecode.co