使用setTimeout返回函数的值

Return value from function whilst using setTimeout

本文关键字:函数 返回 setTimeout 使用      更新时间:2023-09-26

是否有任何方法可以让函数运行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 exit是函数,我写它是为了解释我要做的事情。

我想这样做的原因是我有一个元素,我想通过改变它的不透明度来淡入。

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

我不想把元素传递给这个count函数,因为这意味着当我想要动画元素之外的其他东西时,它限制了它的使用。

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

我认为你要做的是再次调用count方法,如果传递给starttarget的值不一样的话

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