Sleep() in javascript

Asked

Viewed 341 times

0

How would I do something like that?

function blink(){                                        
    let blueBall = document.querySelector('div#blueBall')
    blueBall.style.background = '#028E8E'
    sleep(300)
    blueBall.style.background = '##1dfcfc'
    sleep(300)
    blueBall.style.background = '#cdfefe'
    sleep(300)
    blueBall.style.background = '#028e8e'
}                       

It would be for some "wink" balls, changing color and such...

  • 4

    Use setTimeout, it is not synchronous as a Sleep, are callbacks - read on: https://answall.com/a/45721/3635

  • 2

    In fact, use CSS :)

  • I need to use JS in this :c project

  • A tip, when sharing any question/problem here at Stackoverflow, try to make the problem reproducible. Put the div that would be this "ball" and also some way to perform the function (a button, for example). And one more thing, your second color is with 2 hashtags ##1dfcfc

  • 1

    Thank you so much for the tip, I’m starting in this world of programming, but next question I’ll do it yes

1 answer

1

As Guilherme said in the comments on the issue, to solve your problem just use the function setTimeout, performing a function in a asynchronous after waiting a time in milliseconds. See the example below:

function changeColor() {
    console.log("Alterando a cor para vermelho...");
}

console.log("Cor atual: Azul");
setTimeout(changeColor, 2000);

Now taking the opportunity since I have not seen any other question on the site talking about it, there is a way to perform a wait synchronously in Javascript.

If you really need to hold a hold without the code below running, you can create a Promise that runs the resolve within a setTimeout thus:

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

async function main() {
    console.log('Agora o programa vai "domir" por 2 segundos.');
    await sleep(2000);
    console.log("O programa acaba de acordar :D");
}

main();

As you can see in the code above, the disadvantage of this function sleep is that it can only be used within an asynchronous function since to perform the wait, you need to call the function using the await.

  • 1

    Thank you very much man, solved my problem <3

Browser other questions tagged

You are not signed in. Login or sign up in order to post.