为了账号安全,请及时绑定邮箱和手机立即绑定

在特定时间段内为值设置动画

在特定时间段内为值设置动画

海绵宝宝撒 2021-06-15 17:01:54
我想创建一个从动画值的函数a,以b在x第二并不算难,但我想我是错的或者也许我只是累了,反正我怎么能做到这一点在JavaScript。该函数应类似于以下内容:const varToChange = 0;const amount = 100;const time = 2; // time is in seconds but milisecons are also ok, doesn't really matter.// feel free to add more parameters if necessary.changeValueOverTime(amount, time) {  // magic}预期结果varToChange应100在 2 秒后。
查看完整描述

2 回答

?
明月笑刀无情

TA贡献1828条经验 获得超4个赞

首先,如果您希望对其进行变异,则varToChange不应声明为 with const。其次,使用setTimeout.


let varToChange = 0;

const amount = 100;

const time = 2;

function changeValueOverTime(amount, time) {

  setTimeout(() => {

    varToChange = amount;

  }, time * 1000);

}

changeValueOverTime(amount, time);

setTimeout(() => {

  console.log(varToChange);

}, 3000);

第二个setTimeout在那里,所以你可以看到更新的值varToChange


查看完整回答
反对 回复 2021-06-24
?
HUH函数

TA贡献1836条经验 获得超4个赞

这是我在playcode中创建的函数,也许我应该澄清该函数应该是准确的,该函数总是在给定时间后返回确切的数量。


/**

* @example

* const sub = changeValueOverTime(2, 500, -10320, 1000).subscribe(retrunValues => {

*    valueToChange = changeValueOverTimeHelper(sub, retrunValues);

* });

* @param intevalTime Rate of Change in Milliseconds

* @param time Time to finish in Milliseconds

* @param amount amount that gets added or subtracted from the `initialValue`

* @param initialVaule Initial Value.

*/

function changeValueOverTime(intevalTime: number, time: number, amount: number, initialVaule: number): Observable < [number, boolean, number] > {

  const change = (amount / time) * intevalTime;

  const initialDate = new Date();

  return rxjs.interval(intevalTime).pipe(

    rxjs.operators.map(() => [

      initialVaule + (change * (new Date().getTime() - initialDate.getTime())) / intevalTime,

      new Date().getTime() - initialDate.getTime() >= time ? true : false,

      initialVaule + (change * time) / intevalTime

    ])

  );

}

/**

* @example

* const sub = changeValueOverTime(2, 500, -10320, 1000).subscribe(retrunValues => {

*    valueToChange = changeValueOverTimeHelper(sub, retrunValues);

* });

* @param subscipton Subscription to unsubscribe from when ``returnValues[1]`` is `true`

*/

function changeValueOverTimeHelper(subscipton: Subscription, returnValues: [number, boolean, number]): number {

  if (returnValues[1] === true) {

    subscipton.unsubscribe();

    return returnValues[2];

  } else {

    return returnValues[0];

  }

}


const sub = this.changeValueOverTime(5, 1000, 100, 0).subscribe(retrunValues => {

  console.log(changeValueOverTimeHelper(sub, retrunValues));

});


查看完整回答
反对 回复 2021-06-24
  • 2 回答
  • 0 关注
  • 134 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信