猿问

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

我想创建一个从动画值的函数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 秒后。


海绵宝宝撒
浏览 135回答 2
2回答

明月笑刀无情

首先,如果您希望对其进行变异,则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

HUH函数

这是我在playcode中创建的函数,也许我应该澄清该函数应该是准确的,该函数总是在给定时间后返回确切的数量。/*** @example* const sub = changeValueOverTime(2, 500, -10320, 1000).subscribe(retrunValues => {*&nbsp; &nbsp; 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] > {&nbsp; const change = (amount / time) * intevalTime;&nbsp; const initialDate = new Date();&nbsp; return rxjs.interval(intevalTime).pipe(&nbsp; &nbsp; rxjs.operators.map(() => [&nbsp; &nbsp; &nbsp; initialVaule + (change * (new Date().getTime() - initialDate.getTime())) / intevalTime,&nbsp; &nbsp; &nbsp; new Date().getTime() - initialDate.getTime() >= time ? true : false,&nbsp; &nbsp; &nbsp; initialVaule + (change * time) / intevalTime&nbsp; &nbsp; ])&nbsp; );}/*** @example* const sub = changeValueOverTime(2, 500, -10320, 1000).subscribe(retrunValues => {*&nbsp; &nbsp; valueToChange = changeValueOverTimeHelper(sub, retrunValues);* });* @param subscipton Subscription to unsubscribe from when ``returnValues[1]`` is `true`*/function changeValueOverTimeHelper(subscipton: Subscription, returnValues: [number, boolean, number]): number {&nbsp; if (returnValues[1] === true) {&nbsp; &nbsp; subscipton.unsubscribe();&nbsp; &nbsp; return returnValues[2];&nbsp; } else {&nbsp; &nbsp; return returnValues[0];&nbsp; }}const sub = this.changeValueOverTime(5, 1000, 100, 0).subscribe(retrunValues => {&nbsp; console.log(changeValueOverTimeHelper(sub, retrunValues));});
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答