Delay Async Function Execution

JavaScriptJavaScriptBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will explore how to delay the execution of an asynchronous function in JavaScript. By using the sleep function and returning a Promise, we can put a part of the async function to sleep for a certain amount of time, allowing for better control and management of the code's execution. Through practical examples, we will learn how to effectively implement this technique in real-world scenarios.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript(("`JavaScript`")) -.-> javascript/AdvancedConceptsGroup(["`Advanced Concepts`"]) javascript(("`JavaScript`")) -.-> javascript/ToolsandEnvironmentGroup(["`Tools and Environment`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") javascript/BasicConceptsGroup -.-> javascript/loops("`Loops`") javascript/BasicConceptsGroup -.-> javascript/functions("`Functions`") javascript/AdvancedConceptsGroup -.-> javascript/async_prog("`Asynchronous Programming`") javascript/ToolsandEnvironmentGroup -.-> javascript/debugging("`Debugging`") subgraph Lab Skills javascript/variables -.-> lab-28270{{"`Delay Async Function Execution`"}} javascript/data_types -.-> lab-28270{{"`Delay Async Function Execution`"}} javascript/comp_ops -.-> lab-28270{{"`Delay Async Function Execution`"}} javascript/loops -.-> lab-28270{{"`Delay Async Function Execution`"}} javascript/functions -.-> lab-28270{{"`Delay Async Function Execution`"}} javascript/async_prog -.-> lab-28270{{"`Delay Async Function Execution`"}} javascript/debugging -.-> lab-28270{{"`Delay Async Function Execution`"}} end

How to Delay Execution of an Async Function in JavaScript

To delay the execution of an asynchronous function in JavaScript, you can use the sleep function below, which returns a Promise that resolves after a certain amount of time. Here's an example of how to delay the execution of part of an async function using sleep:

const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

async function sleepyWork() {
  console.log("I'm going to sleep for 1 second.");
  await sleep(1000);
  console.log("I woke up after 1 second.");
}

To use this function, simply call sleepyWork() and the console will log the messages with a 1 second delay between them.

Summary

Congratulations! You have completed the Delay Async Function Execution lab. You can practice more labs in LabEx to improve your skills.

Other JavaScript Tutorials you may like