Javascript - Wait the true ending of a function that uses setTimeout

眉间皱痕 提交于 2019-12-11 07:53:24

问题


Let me explain my problem with a dummy situation. Let's consider the following code :

var counter = 0;    
function increase(){
    if(counter < 10){
        counter++;
        setTimeout(increase, 100);
    }
}

Now, the idea is to display the counter value once the increase() function has finished its job. Let's try this :

increase();
alert(counter);

As you probably know, it doesn't work. The alert() call displays 1, not 10. I would like to display the value of counter once the function has entierly finished its job of incrementing it.

Is there a simple way to solve my problem ?

[Note] Using a callback function is NOT an option, since I don't want increase() to know that I would like to do something after it's done (for modularity purposes). So, I'd like to AVOID something like this :

function increaseForTheKings(f){
    if(counter < 10){
        counter++;
        setTimeout(function(){ increase(f); }, 100);
    } else {
       f();
    }
}

回答1:


The standard way to do this is with promises.

var counter = 0;
function increase(){
  var d = jQuery.Deferred();
  var doIncrease = function() {
    if(counter < 10){
        counter++;
        setTimeout(doIncrease, 100);
    } else {
      d.resolve();
    }
  };
  doIncrease();
  return d.promise();
};

increase().then(function() {
  alert(counter);
});



回答2:


As far as I know, there's only so much you can do when dealing with asynchronous operations. If you want to avoid a callback, I'd say go with promises. Actually, I'd say use promises anyway :)



来源:https://stackoverflow.com/questions/18625439/javascript-wait-the-true-ending-of-a-function-that-uses-settimeout

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!