madas
madas

Reputation: 73

javascript function need to be continue after settimeout

I have a JavaScript function; from that am calling a delay function.

function(){
  // code

  doDelay();

  // some other functionality....
}

function doDelay(){
   setTimeout(function() {alert("after wait");}, 10000);
}

after waiting 10 seconds alert is coming after wait. but its not again continue the some other functionality.... of my main function.. After delay I want to execute the remaining functionality. How can I do that?

Upvotes: 1

Views: 7495

Answers (3)

slebetman
slebetman

Reputation: 113994

The setTimeout function does not delay execution. Instead, it schedules a function to be executed at a later time. To do what you want you need to change your code to this:

function(){
...
...
    doDelay(function(){

      some other functionality....

    });
}

function doDelay(callback){
    setTimeout(function() {callback()}, 10000);
}

Indeed, javascript already has a doDelay function. It's called setTimeout:

function(){
...
...

    setTimeout(function(){

      some other functionality....

    },10000);
}

If you want the outer function to also delay execution of code that comes after it, you also need to pass a callback to it:

function foo (callback){
...
...
    doDelay(function(){

      some other functionality....

      callback();

    });
}

So that, for example, it allows you to rewrite something like this:

foo();
// do other stuff after foo...

to this:

foo(function(){
    // do other stuff after foo...
});

You basically need to restructure your logic around callbacks.

Upvotes: 3

Narendra Pathai
Narendra Pathai

Reputation: 41975

doDelayAndThenContinue(){
          setTimeout(function() {alert("after wait"); 
              //do other functionality here
          }, 10000);

     }

Remove the do other functionality from main method and put in setTimeout

Upvotes: 0

LDJ
LDJ

Reputation: 7314

Can't you wrap the other functionality in another function, then from your SetTimeout call that function?

 function(){
  doDelay();
}

function doDelay(){
  setTimeout(function() {alert("after wait");andTheRest();}, 10000);
}

function andTheRest(){
  //Rest of the stuff here
}

Upvotes: 0

Related Questions