一个抽奖H5页面的记录

好久没有写博客了,应该不叫好久,应该是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);
  });
}

后面把整个功能优化了,想到后面这种活动也会用到。所以就优化了下增加易用性


posted @ 2020-11-11 17:13  marvine  阅读(759)  评论(0编辑  收藏  举报