Javascript - 等待使用 setTimeout 的函数的真正结束 [英] Javascript - Wait the true ending of a function that uses setTimeout

查看:30
本文介绍了Javascript - 等待使用 setTimeout 的函数的真正结束的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我用一个虚拟的情况来解释我的问题.让我们考虑以下代码:

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);
    }
}

现在,我们的想法是在 increase() 函数完成其工作后显示计数器值.让我们试试这个:

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

increase();
alert(counter);

您可能知道,它不起作用.alert() 调用显示 1,而不是 10.一旦函数完全完成其递增工作,我想显示 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 ?

[注意]使用回调函数不是一种选择,因为我不希望 increase() 知道我想在完成后做某事(出于模块化目的).所以,我想避免这样的事情:

[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();
    }
}

推荐答案

执行此操作的标准方法是使用 承诺.

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);
});

这篇关于Javascript - 等待使用 setTimeout 的函数的真正结束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆