I want to force a function to wait 1 second before she continues after to do that in javascript . For example:
function DoSomething(){
// wait 1 second
//continue w.e is this function does.
}
Thanks.
To force a 1 second pause or delay in JavaScript we can use the setTimeout function, but if we want a better solution we should use the Promise function.
To delay a function execution in JavaScript by 1 second, wrap a promise execution inside a function and wrap the Promise's resolve() in a setTimeout() as shown below. setTimeout() accepts time in milliseconds, so setTimeout(fn, 1000) tells JavaScript to call fn after 1 second.
Create a Simple Delay Using setTimeoutlog("Hello"); setTimeout(() => { console. log("World!"); }, 5000); This would log “Hello” to the console, then make JavaScript wait 5 seconds, then log “World!” to the console.
The Complete Full-Stack JavaScript Course! To delay a function call, use setTimeout() function. functionname − The function name for the function to be executed. milliseconds − The number of milliseconds.
If i understand you right , you need this:
setTimeout(DoSomething ,1000);
Edit , thanks to Teemu:
function DoSomething (){
setTimeout(ContinueDoSomething ,1000);
}
function ContinueDoSomething (){
// ...
}
And even one more way , may be most effective in some cases:
function DoSomething (){
setTimeout( function(){
// ...
},1000);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With