最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Execute after setTimeout finished - Stack Overflow

programmeradmin0浏览0评论

Probably not very suitable title, but the question is the following.

I've got this piece of code

var someprogram = function(){ if(stopprocess) return; //do things setTimeout(someprogram, 1000); } setTimeout(someprogram, 1000);

Sofar it works. After some number ot iterations, lets say 12, stopprocess is true and whole thing stops. I want to do some more things after the return. So the question is what is the best way to rewrite the structute to be able to do so? Because I need the timeout, but I don't know how else to stop the whole thing without using a return-statement. Any ideas? (I have only one javascript file for this task)

Probably not very suitable title, but the question is the following.

I've got this piece of code

var someprogram = function(){ if(stopprocess) return; //do things setTimeout(someprogram, 1000); } setTimeout(someprogram, 1000);

Sofar it works. After some number ot iterations, lets say 12, stopprocess is true and whole thing stops. I want to do some more things after the return. So the question is what is the best way to rewrite the structute to be able to do so? Because I need the timeout, but I don't know how else to stop the whole thing without using a return-statement. Any ideas? (I have only one javascript file for this task)

Share Improve this question asked Mar 20, 2015 at 9:26 user4065758user4065758 3193 silver badges12 bronze badges 3
  • 1 callback function as argument or just execute simple function? – StateLess Commented Mar 20, 2015 at 9:27
  • jsfiddle/arunpjohny/os26vgc5/1 – Arun P Johny Commented Mar 20, 2015 at 9:30
  • jsfiddle/arunpjohny/os26vgc5/2 – Arun P Johny Commented Mar 20, 2015 at 9:32
Add a ment  | 

2 Answers 2

Reset to default 5

there are many ways to do this simple way is to write all your logic in a function and execute it.

    var logic = function(){
       //do things 
     }

and execute it before return

var someprogram = function(){
    if(stopprocess){ 
       logic(); // your code is executed now
       return;
   }

    setTimeout(someprogram, 1000);
}
setTimeout(someprogram, 1000);

May be this one works for you:

var someprogram = function() { 
    if(stopprocess) {
        //do the rest

    } else {
        //do things 
        setTimeout(someprogram, 1000); 
    }
} 

setTimeout(someprogram, 1000);
发布评论

评论列表(0)

  1. 暂无评论