有的時候咱們想實現一個數字從a逐漸遞增到b的跳動效果,若是用rxjs
的話就能夠輕鬆實現。廢話很少說直接上源碼:code
import { Observable } from 'rxjs/Observable'; import 'rxjs/add/observable/interval'; import 'rxjs/add/operator/take'; import 'rxjs/add/operator/scan'; // start: 開始數字 end: 結束數字 duration: 持續時間 interval: 跳動幾回 cb: 回調 export function jump({ start, end, duration = 300, interval = 10, cb }) { const delta = Math.abs(end - start); const sign = Math.sign(end - start); const numberIncrease = Math.floor(delta / interval); const timeIncrease = duration / interval; Observable .interval(timeIncrease) .take(interval) .scan((acc) => acc + (numberIncrease * sign), start) .subscribe({ next: (n) => { cb(n); }, // 用complete保證數字最終會變爲end complete: () => { cb(end); }, }); }