好久沒有寫博客了,應該不叫好久,應該是long long years ago。因最近幫個朋友改了個bug,覺得應該記錄下這個過程。
說是解決bug,毋寧說是把頁面功能完成。
發現問題所在
拿到代碼先跑一下,發現能跑。但是哪里怪怪的,是一個抽獎H5游戲,就是那種九宮格轉圈抽獎的那種,但是在點擊開始后結果都出來了但還在轉圈。顯示上沒有和抽獎的結果同步,看了下代碼。原來是開始和結束是用setTimeout這個定時器來控制同步的,這樣顯然會有問題。
我的解決思路是:
- 只要一個啟動方法控制開始和結束
- 在啟動時就直接傳入停留的格子位置(即抽獎結果)
在啟動函數加了個promise,當請求接口獲取結果后即調用啟動函數。在回調中設置結束狀態,這樣就不用依賴定時器造而成不同步的問題。
不說那么多了直接上代碼:
export default class Lucky {
constructor(page) {
this.role = [0, 1, 2, 5, 8, 7, 6, 3];
this.timmer = null;
this.currentIndex = 0;
this.speed = 100;
this.page = page;
this.djs = 3;
this.djsFlag = false;
this.luckyIndex = null;
this.status = false;
}
startGame(index) {
const that = this;
return new Promise((resolve, reject) => {
that.luckyIndex = index;
that.timmer = setInterval(() => {
if (that.status) {
that.page.deng_status = true;
} else {
that.page.deng_status = false;
}
that.status = !that.status;
that.page.items.forEach(item => {
item.active = false;
});
that.currentIndex += 1;
if (that.currentIndex === that.role.length) {
that.currentIndex = 0;
}
if (that.luckyIndex !== null && that.luckyIndex === that.currentIndex) {
that.djs -= 1;
that.speed += 1000;
}
const obj = that.page.items[that.role[that.currentIndex]];
obj.active = true;
that.page.$set(that.page.items, that.role[that.currentIndex], obj);
if (that.djs === 0) {
clearInterval(that.timmer);
that.stopGame(that.luckyIndex);
that.timmer = null;
that.reset();
// 判斷是否可以繼續
that.page.canClick = that.page.times > 0;
that.page.deng_status = false;
resolve();
}
}, that.speed);
});
}
stopGame(index) {
this.djsFlag = true;
}
reset() {
this.djsFlag = false;
this.luckyIndex = null;
this.djs = 3;
this.speed = 100;
}
}
在抽獎中這樣調用
if (that.result.prize === '謝謝參與') {
that.lucy.startGame(obj_hash[idx]).then(() => {
that.setFails(true);
});
} else {
that.lucy.startGame(obj_hash[idx]).then(() => {
that.setSuccess(true);
});
}
后面把整個功能優化了,想到后面這種活動也會用到。所以就優化了下增加易用性