JavaScript's prime sleep function

I am in need of a sleep function for my JavaScript code. I could use a promise-based function, but it requires the await keyword to function correctly. The issue is that I need to use the sleep function at the top level of my code.

function sleep(milliseconds) {
    return new Promise(resolve => setTimeout(resolve, milliseconds));
}

await sleep(5) //invalid

Since JavaScript does not support await at the top level, I'm unable to write await sleep(5).

Is there a way to implement a function that will perform like this?


let i = 10;
while (i > 0) {
    console.log("sleeping..." + i);
    sleep(1);
    i--;
}

console.log("Hello");

sleep(5);

console.log("World");

Any suggestions on how to achieve this?

Answer №1

Support for top-level await has been added to Ecmascript Modules. For those utilizing Node.js, a simple way to make this transition is by changing the file extension from .js to .mjs.

If that's not an option, the alternative is to enclose your code within a function.

Answer №2

Without top-level awaits, wrapping is necessary to achieve the desired result.

One alternative is to utilize .then for asynchronous operations.

function sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

sleep(2000).then(() => {
  //All necessary logic should be contained within this block
});

Another approach is to use an IIFE (Immediately Invoked Function Expression).

function sleep(milliseconds) {
  return new Promise(resolve => setTimeout(resolve, milliseconds));
}

(async () => {
  await sleep(3000);
  //All necessary logic should be contained within this block

})();

Answer №3

While it may sound unconventional and not recommended, it is indeed possible to achieve this by utilizing the Date.now() function.

function pause(seconds) {
    const start = Date.now();
    while (Date.now() - start < seconds * 1000) {}
}

This function essentially checks the difference between the current time and the start time based on the specified duration. Using a while loop in this manner will essentially block the main thread, delaying the execution of subsequent lines of code until the thread is released.

I hope this explanation is helpful.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Dynamic web elements can be easily enhanced through the use of jQuery

Upon loading a page through AJAX, I encountered the following code involving animation of a div (#1 moves it to the left and #2 moves it back): #1 $('#flipper').click(function () { $(".l-l").animate({ "left": -267 }, 600, function () { ...

Unlocking keys of JavaScript class prior to class initialization

My constructor was becoming too large and difficult to maintain, so I came up with a solution to start refactoring it. However, even this new approach seemed bulky and prone to errors. constructor(data: Partial<BusinessConfiguration>) { if(!d ...

Triggering the open() function within an Ajax request

Upon experimenting with the method open(), I discovered that it requires a URL file as an argument. For instance, I have two functions named generateGeometricShapes() and colorShapes(). I am contemplating whether I should create separate files for each fu ...

Creating a dynamic table using jQuery and XML content

Hello everyone, I am new to jQuery and JavaScript in general. My goal is to generate a table based on XML data, but I'm struggling to achieve the correct output. Here's what I have tried so far: Here is my HTML code: <table id="daily_fruit"& ...

Having trouble with arrays in JavaScript - receiving TypeError when trying to set a property

Issue: An error has occurred - Uncaught TypeError: Cannot set property '0' of undefined Snippet of relevant code: var field = new Array(6); for(var x=0; x<field.length; x++){ field[x] = new Array(12); for(var y=0; y<field[x].length; y ...

Breaking down a string into an array using Node.js

Is there a way to change the following text into an array using nodejs? "Content: [{id: 1, value: 1, number: 1},{id: 13, value: 1, number: 3},{id: 14, value: 1, number: 3},]" I attempted to use JSON.parse, but encountered this error: Unexpected token c i ...

The `getScript` function in jQuery is not working as expected, even though the path is accurate and the script was successfully downloaded

Recently, I created a website using Mustache.js and incorporated templates loaded via AJAX with jQuery. During the testing phase on my local environment, everything worked perfectly. However, upon uploading the site to my school server, an issue arose whe ...

Execute HTML and JS files through Eclipse PDT to view in a web browser

Is it possible to open HTML and JS files in a web browser within Eclipse PDT? Right now, only PHP files seem to launch successfully, otherwise an "Unable to Launch" dialog pops up. Any advice is appreciated! ...

Exploring portfinder in Javascript: A guide to its usage

As a newcomer to Javascript, I am eager to figure out how to utilize the portfinder.getPort() function within one of my functions in order to generate a random port each time. The code snippet below showcases my current implementation: var portfinder = re ...

Ways to troubleshoot the "TypeError: Cannot read property 'value' of null" issue in a ReactJS function

I keep encountering a TypeError: Cannot read property 'value' of null for this function and I'm struggling to pinpoint the source of the issue. Can someone help me figure out how to resolve this problem? By the way, this code is written in R ...

The assets path is the directory within the installed package that houses the main application files following the completion of a

I have a Vue.js UI component that is internally built using webpack. This reusable UI component library references its images as shown below: <img src="./assets/logo.png"/> <img src="./assets/edit-icon.svg"/>   <i ...

Counting the occurrence of a specific class within an element using jQuery

Within my table, each row is assigned one or more classes based on its region. This is the structure of my table: <table> <thead> <th>Title</th> <th>Name</th> </thead> <tbody> <tr class="emea ...

Converting a JS result set into JSON format

Having an issue with converting code from XML output to a JSON object instead. Here is the current code: public String evaluate() throws Exception { // Code block here } I need assistance in using GSON JSON utility methods to convert the result s ...

What could be causing the error message "setShowModal is undefined" to appear in my React project?

Here is the code snippet I am working on: import React, { useState } from "react"; import Modal from "./Modal"; function displayModal() { setShowModal(true); } export default function NewPostComponent() { const [showModal, setShowMod ...

Getting a null value for active user after completing the sign-in process

I am using local storage to store username and password. However, I am encountering an issue where the active user is returning null after a certain line of code, and I am unsure why. console.log("I am the Active user: " + activeUser); const me ...

Troubles encountered during the installation of Visual Web Developer 2010?

Here is the situation I'm facing: After encountering some issues with PHP while working on an ASP.net project, I decided to reinstall everything. The installation of Apache, MySQL, and PHP went smoothly, but now I seem to be facing some problems. I ...

Is it true that Redux Saga's select function returns mutable state?

Is the state returned by Redux Saga's select function mutable or immutable? To learn more, visit https://github.com/redux-saga/redux-saga ...

Could the absence of a tree view in the div be due to an error in the positioning of the DOM

I'm currently working on displaying a tree structure with specific child elements inside a div using JavaScript and HTML. Despite creating all the necessary objects and ensuring that the data is correctly read from the JSON file (refer to the "data" i ...

Is there a way to show a 'Refresh' icon in HTML without the need to download an image through HTTP?

In my HTML/JavaScript app project, I am looking to incorporate a 'refresh' symbol without having to load an image through HTTP requests. Are there reliable methods that can achieve this across all major browsers? I came across the Unicode value: ...

The visibility of buttons can be controlled based on the selected radio option

I have just completed setting up 4 buttons (add, edit, delete, cancel) and a table that displays data received via ajax. Each row in the table contains a radio button identified by the name "myRadio". When a radio button is clicked, I need the buttons to ...