/** |
* Created by wangyy on 2016/12/26. |
*/'use strict';class NumberAnimate { |
|
constructor(opt) { |
let def = { |
from:50,//開始時的數字 |
speed:2000,// 總時間 |
refreshTime:100,// 刷新一次的時間 |
decimals:2,// 小數點後的位數 |
onUpdate:function(){}, // 更新時回調函數 |
onComplete:function(){} // 完成時回調函數 |
} |
this.tempValue = 0;//累加變量值 |
this.opt = Object.assign(def,opt);//assign傳入配置參數 |
this.loopCount = 0;//循環次數計數 |
this.loops = Math.ceil(this.opt.speed/this.opt.refreshTime);//數字累加次數 |
this.increment = (this.opt.from/this.loops);//每次累加的值 |
this.interval = null;//計時器對象 |
this.init(); |
} |
init(){ |
this.interval = setInterval(()=>{this.updateTimer()},this.opt.refreshTime); |
} |
|
updateTimer(){ |
|
this.loopCount++; |
this.tempValue = this.formatFloat(this.tempValue,this.increment).toFixed(this.opt.decimals); |
if(this.loopCount >= this.loops){ |
clearInterval(this.interval); |
this.tempValue = this.opt.from; |
this.opt.onComplete(); |
} |
this.opt.onUpdate(); |
} |
//解決0.1+0.2不等於0.3的小數累加精度問題 |
formatFloat(num1, num2) { |
let baseNum, baseNum1, baseNum2; |
try { |
baseNum1 = num1.toString().split(".")[1].length; |
} catch (e) { |
baseNum1 = 0; |
} |
try { |
baseNum2 = num2.toString().split(".")[1].length; |
} catch (e) { |
baseNum2 = 0; |
} |
baseNum = Math.pow(10, Math.max(baseNum1, baseNum2)); |
return (num1 * baseNum + num2 * baseNum) / baseNum; |
};}export default NumberAnimate; |