有的时刻我们想完成一个数字从a逐步递增到b的跳动结果,假如用rxjs
的话就能够轻松完成。空话不多说直接上源码:
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);
},
});
}