Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

force wait in javascript [duplicate]

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.

like image 346
Ori Refael Avatar asked Jun 11 '13 10:06

Ori Refael


People also ask

How do I force JS to wait?

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.

How do you wait for 1 second in JavaScript?

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.

How do you wait for 5 seconds in JavaScript?

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.

How do you make a delay in JavaScript?

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.


1 Answers

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);
}
like image 199
Ivan Chernykh Avatar answered Oct 18 '22 12:10

Ivan Chernykh