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
.
Use setTimeout, it is not synchronous as a Sleep, are callbacks - read on: https://answall.com/a/45721/3635
– Guilherme Nascimento
In fact, use CSS :)
– bfavaretto
I need to use JS in this :c project
– IgorPatricio
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
– Rafael Tavares
Thank you so much for the tip, I’m starting in this world of programming, but next question I’ll do it yes
– IgorPatricio