使用setTimeout时从函数返回值

时间:2015-10-20 06:04:57

标签: javascript

有没有办法让函数与setTimeout一起运行并返回赋给变量的值?

我的意思是这样的例子:

function count(start, target) {
  if (start < target) {
    start += 0.1;
    return start;
  } else if (start > target) {
    return target;
  }
  // i'm fully aware the return above will prevent this line occur
  // this is my issue currently
  setTimeout(function () {
    count(start, target)
  }, 1000);
}

var el = document.getElementById('test');
var value = count(0.0, 1.0); //get the opacity value

function check() {
  el.style.opacity = value; //assign what the value is in this moment
  if (value != 1.0) {
    setTimeout(check, 0);
  }
}

check();

我知道这段代码按照我想要的方式工作,因为return退出了这个功能,我写这篇文章是为了解释我想要做的事情。

我想以这种方式做到这一点的原因是因为我想要通过改变它的不透明度来淡化它。

所以我有一个函数可以使用我想要的缓和量将起始值增加到目标值,然后返回将分配给元素的opacity属性的所述值。

我不想将该元素传递给此count函数,因为这意味着它限制了它的使用,因为我想要为元素之外的其他内容添加动画。

这个问题的解决方案是什么?

1 个答案:

答案 0 :(得分:1)

我认为您要尝试的是,如果countstart传递的值不相同,则再次调用target方法

function count(start, target) {
    var ret;

    if (start < target) {
        ret = start + 0.1;
    } else if (start > target) {
        ret = target;
    }

    if (start != target) {
        setTimeout(function () {
            count(ret, target)
        }, 1000);
    }
    return ret;
}
相关问题