Asynchronous JavaScript without a built-in asynchronous method

96 Views Asked by At

All examples I see about Asynchronous JavaScript when they use callbacks, promises or async/await with a delay, to fake examples like waiting for something, make use of setTimeout() or setInterval(). What if I don't get in a callback, promise or async/await an allready built-in asynchronous code? I want to fake the delay, and can do it with Date() in a synchronous way.

It's not a question just about how to sleep/delay without using setTimeout() or setInterval(). This is just an example, and like to see asynchronous JavaScript code without invoking a built-in asynchronous method.

My synchronous code is:

const sleep = (milliseconds) => {
    let t0 = Date.now();
    const t1 = Date.now() + milliseconds;
    console.log(`Sleeping ${milliseconds} milliseconds`);
    while (t0 <= t1) {
        t0 = Date.now();
    }
};

const randomMilliseconds = () => {
    return Math.round(Math.random() * 10000);
};

const returnElement = () => {
        sleep(randomMilliseconds());
        console.log(element);
    };

const elements = [1, 2, 3, 4, 5];

function loopElements() {
    for (element of elements) {
        returnElement();
    }
}

loopElements();

I read about async functions and thought I could do this with loopElements() or returnElement(), but wasn't able to do it. Also all examples I see about async looping are with setTimeout() or use other built-in async solutions like fetching data from an API.

Can this be done? And just with a simple Date() example.

1

There are 1 best solutions below

4
Quentin On

You can't.

You get asynchronous functionality when you use asynchronous features.

If you restrict yourself to synchronous features then you can only get synchronous results.