Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
March 28, 2023 08:58 pm

How to Wait in JavaScript?


It is very common when developing websites or applications to either wait for a specific time or wait for something specific to complete. There are many techniques that you can use to wait in JavaScript. In this tutorial, you will learn about different methods and concepts that you can use to wait and when you should use which one.


Do Something After a Specific Time


One of the most common types of wait in JavaScript is the one where you wait for a specific amount of time to pass before taking any action.


For example, let's say someone visits your website. It would be very annoying to show them a popup to sign up for your newsletter or to subscribe to your YouTube channel as soon as they load a webpage. A better strategy would be to wait for a particular amount of time like a minute and then show the popup.


It is very easy to do this type of wait in JavaScript. All you need to do is use the setTimeout() method. Here is an example:



















































1
console.log("Hello!");
2

3
setTimeout(function() {
4
  console.log("Sign Up for the Newsletter");
5
}, 5000);
6

7
/* Output

8


9
11:01:27.165 Hello!

10
11:01:32.184 Sign Up for the Newsletter

11


12
*/

You can add this waiting period anywhere you like. For example, once a user clicks a button, you can use setTimeout() to only take action after a specific time period.



































































1
const delay_btn = document.querySelector("button.delay-click");
2

3
delay_btn.addEventListener("click", function() {
4
  console.log("I was clicked!");
5
  
6
  setTimeout(function(){
7
    console.log("I am responding!");
8
  }, 2000);
9
});
10

11
/* Output

12


13
11:12:31.228 I was clicked!

14
11:12:33.236 I am responding!

15


16
*/

In the above example, we could detect the click as soon as it happened. However, it is still possible to respond to the click after some time has passed. The setTimeout() method makes sure that the response happens after 2 seconds.


Do Something After Fixed Time Intervals


Let's say you are developing a game where you have to spawn enemies after every three seconds or you are building an app where you remind users to  take some action after every 30 minutes. The setInterval() method works great in this case because it can execute tasks repeatedly after a fixed time delay between them.


Here is an example:







































































1
setInterval(function() {
2
  console.log("Spawn New Enemy!");
3
}, 3000);
4

5
setInterval(function() {
6
  console.log("Spawn Power Up!");
7
}, 4000);
8

9
/* Output

10


11
11:26:19.526 Spawn New Enemy!

12
11:26:20.520 Spawn Power Up!

13
11:26:22.529 Spawn New Enemy!

14
11:26:24.532 Spawn Power Up!

15
11:26:25.532 Spawn New Enemy!

16


17
*/

As you can see, a new enemy spawns every three seconds and a power up spawns every four seconds.


In certain situations, you might also want to stop performing a task based on specific triggers. The clearInterval() method comes to our rescue in this case.


Any call to the setInterval() method returns a unique interval ID that we can store in a variable. After that, we can stop the repeated execution of this interval by passing the interval ID to the clearInterval() method. You will understand this better with the example below where we create a countdown timer.















































































1
let timer_duration = 100;
2
let timer_interval_id;
3

4
start_btn.addEventListener('click', function() {
5
  timer_interval_id = setInterval(function(){
6
    timer_duration -= 1;
7
    
8
    heading.innerText = timer_duration;
9
  }, 1000);
10
});
11

12
stop_btn.addEventListener('click', function() {
13
  clearInterval(timer_interval_id);
14
});
15

16
reset_btn.addEventListener('click', function() {
17
  timer_duration = 100;
18
  heading.innerText = timer_duration;
19
});

Our countdown timer is set to count downwards from 100. We have attached click listeners to three different buttons. The "Start Timer" button starts our countdown timer with the help of the setInterval() method. The code inside setInterval() is executed every second and we reduce the value of timer_duration by 1 after each iteration. This interval is then assigned to the variable timer_interval_id.


We use the clearInterval() method to clear this interval when the "Stop Timer" button is pressed. The following CodePen demo shows out countdown timer in action:



Wait for a Task to Complete Before Proceeding


In the previous example,  we updated the text inside our heading after subtracting 1 from our timer_duration. Our heading was therefore updated with new duration. All this happened very quickly and the commands were executed one after the other as expected.


However, some operations can take a while to complete. For example, you might be getting the data about weather for a place from an API. In this case, you would ideally like to wait for the data access operation to complete before updating the UI.


We will now learn how to wait for a task to complete before we proceed with the executions of our program. Here is a simple code snippet where some friends are supposed to meet at a spot and then go to the movies together.























































































1
function sandy_is_late() {
2
  setTimeout(function () {
3
    console.log("Sandy reached the spot a little late.");
4
  }, 2000);
5
}
6

7
function everyone_go() {
8
  console.log("Amanda, Liam and John have arrived at the waiting spot.");
9
  sandy_is_late();
10
  console.log("Everyone has left for the movies now!");
11
}
12

13
everyone_go();
14

15
/* Outputs:

16


17
Amanda, Liam and John have arrived at the waiting spot.

18
Everyone has left for the movies now!

19
Sandy reached the spot a little late.

20
 

21
*/

When we call the everyone_go() function, we expect everyone to go to the movies when all the friends have arrived at the waiting spot. However, executing the code shows that everyone had already left for the movie before Sandy arrived.


How can we remedy that?


A simple solution here involves the use of the Promise object as well as async functions and the await keyword. I will briefly explain all of them here.


The Promise object in JavaScript helps you keep track of any asynchronous tasks in your program.


So, what are asynchronous tasks? Some tasks that you implement in programming can take a while to provide results. In such cases, you don't want your program to freeze completely, and still respond to other events. This is accomplished by making the tasks asynchronous.


This means that we can use promises to determine the state of our tasks and whether they have completed successfully. The async and await keywords allows us to write that promise-based code in a clear manner. Here is our updated code and its output:







































































































1
function sandy_is_late() {
2
  return new Promise((resolve) => {
3
    setTimeout(() => {
4
      console.log("Sandy reached the spot a little late.");
5
      resolve();
6
    }, 2000);
7
  });
8
}
9

10
async function everyone_go() {
11
  console.log("Amanda, Liam and John have arrived at the waiting spot.");
12
  await sandy_is_late();
13
  console.log("Everyone is going to the movies now!");
14
}
15

16
everyone_go();
17

18

19
/* Outputs:

20


21
Amanda, Liam and John have arrived at the waiting spot.

22
Sandy reached the spot a little late.

23
Everyone has left for the movies now!

24
 

25
*/

The everyone_go() function has only undergone minor changes. We added the keyword async before the function. This allows us to use the await keyword inside our function definition. The function everyone_go() also returns a Promise but we won't need that here.


The sandy_is_late() function now explicitly returns a Promise which is resolved after two seconds due to the setTimeout() method.


You might have noticed that there is an await keyword before our sandy_is_late() function call. This suspends the parent function execution until the promise is resolved. Therefore, it was important for us to call resolve() within our setTimeout() method.


Once the promise was resolved, we logged our next statement to the console.


Writing a Waiting Function in JavaScript


One nice thing about promises is that we can call the then() method on them when our promise has been fulfilled. The callback functions that you provide to this method are called when the promise has settled.


This then() method itself returns a Promise object which makes it easier to keep chaining more then() methods and let all your tasks happen in a sequential manner.


All that we need to do to write a general waiting function is create and return a promise that resolves after specified number of seconds. Here is an example:























1
function wait(t) {
2
  return new Promise((resolve) => {
3
    setTimeout(resolve, 1000 * t);
4
  });
5
}

Our wait() function accepts a single parameter that determines the number of seconds we have to wait. After that, we call setTimeout() with the specified time and make a call to resolve() within this method. This resolves our promise and paves way for any further calls to then().







































































1
console.log("Hey");
2

3
wait(2)
4
  .then(() => console.log("Are you free tonight?"))
5
  .then(() => wait(2))
6
  .then(() => console.log("Alright, Bye!"));
7

8
console.log("How are you?");
9

10
/* Outputs

11


12
18:56:27.228 Hey

13
18:56:27.230 How are you?

14
18:56:29.244 Are you free tonight?

15
18:56:31.249 Alright, Bye!

16


17
*/

In this example, we used our wait() function to a 2 second delay between our console.log() calls. One thing worth noticing is that wait() doesn't stop the execution of the whole program. Our last statement was still logged just after "Hey".


Anything that you want to execute with delay has to be wrapped within a then() call.


Final Thoughts


In this tutorial, we learned about different ways of waiting in JavaScript. The best technique to use will depend on your requirements. You can use the setTimeout() method when you want to execute something after a specific time. The setInterval() method is useful when you want to execute something periodically.


Finally, promises are helpful when you don't know how long a task will take and want to execute some code after that specified task has completed. One advantage of using promises is that they allows you to wait for tasks to complete without freezing the whole program.



Original Link: https://code.tutsplus.com/tutorials/how-to-wait-in-javascript--cms-106747

Share this article:    Share on Facebook
View Full Article

TutsPlus - Code

Tuts+ is a site aimed at web developers and designers offering tutorials and articles on technologies, skills and techniques to improve how you design and build websites.

More About this Source Visit TutsPlus - Code