0

I have a problem. My code doesn't work. It doesn't display the last essage in the console.log (the "end"). I use a setTimeout promise to do one thing every 3000ms. Here is my promise function setTimeOut

function delay(message){
    return new Promise(() => setTimeout(function () {
        console.log(message)
    }, 3000))
}

That I use in an async function in my code :

async () => {
    while (true) {
        console.log("Start")
        await delay("No")
        console.log("End")
    }
}

I make my code more easier (without all the conditions and the functions that I have to call) because I think I've missed something in my understanding of the promise maybe. What am i doing wrong?

Could you please help me for this?

3
  • Where’s the definition of timeout and where is delay used? You forgot to resolve the promise in delay. Commented Aug 31, 2020 at 18:16
  • 1
    Does this answer your question? Promise will not resolve Commented Aug 31, 2020 at 18:18
  • Sorry, I changed the name of the function to post it, but timeout and delay are the same function Commented Aug 31, 2020 at 18:22

1 Answer 1

3

Your promise in delay/timeout function never resolves.

Here's how it will work. Note the resolve parameter of the promise callback.

function delay(message) {
    return new Promise((resolve) => setTimeout(function () {
        console.log(message);
        resolve();
    }, 3000))
}
    
(async () => {
    while (true) {
        console.log("Start")
        await delay("No")
        console.log("End")
    }
})();

Sign up to request clarification or add additional context in comments.

2 Comments

Ok, I got it, thank you for your help. I misuse the promise, now I'm starting to understand how it works.
I just had an issue with an while + async function use. Doing a DOM manipulation and checking the result repeatedly in while gives incorrect results. Probably due to the render time. I solved the issue with a recursive approach, but this is more practical. Adding a delay after the modification works.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.