“完美”解決微信小程序購物車拋物動畫,在連續點擊時出現計算錯誤問題,定時器停不下來。


最近做,微信點餐小程序,遇到添加商品時出現拋物動畫,參考借鑒了這位大神的方法

https://www.cnblogs.com/greengage/p/7815842.html

但出現了一個問題,連續點擊加入購物車時,拋物動畫報錯。如圖:

我的解決方法是:

//購物車拋物動畫 (時間間隔)(解決點擊過於頻繁時,拋物動畫報錯問題)
     var nowTime = new Date().getTime();
      var clickTime = e.currentTarget.dataset["ctime"];      
      if (clickTime != 'undefined' && (nowTime - clickTime < 1500)) {        
        wx.showToast({
          title: '操作過於頻繁',
          icon: 'loading',
          duration: 1000
        })
      } else {
        _that.setData({
          ctime: nowTime
        })       
        _that.touchOnGoods(e);        
      }                 

 以上方法是臨時上線想到的,但並不是最好的解決方法,還影響用戶體驗。假如用戶就是要連續點擊,那么能不能連續創建多個拋物小球呢?答案是可以的,其實連續創建小球,上面那位大神【鏈接】的代碼中已經寫好了。

問題分析:看上一次瀏覽器拋出的錯誤,如下

這個錯誤什么意思呢?根據查找,最終定位 【startAnimation】這個方法中的 【setInterval】方法,“x” of undefined  ,x未定義,指的是 bezier_points[index]['x'] 在取值時,因為 index 的值超出了范圍導致在獲取x的值時顯示未定義。

經過改造(代碼如下)哈哈,只用修改這里就好了,之前的阻斷連續點擊的代碼可以去掉了:

 1     // this.timer = setInterval(function () {
 2     //   index--;
 3     //   that.setData({
 4     //     bus_x: bezier_points[index]['x'],
 5     //     bus_y: bezier_points[index]['y']
 6     //   })
 7     //   if (index < 1) {
 8     //     clearInterval(that.timer);
 9     //     that.setData({
10     //       hide_good_box: true
11     //     })
12     //   }
13     // }, 25);
14 
15     this.timer = setInterval(bus_set,25);
16     function bus_set(){    
17       for (let i = index-1; i > -1; i--) {      
18         that.setData({
19           bus_x: bezier_points[i]['x'],
20           bus_y: bezier_points[i]['y']
21         })
22         if (i < 1) {
23           clearInterval(that.timer);
24           that.setData({
25             hide_good_box: true
26           })
27         }
28       }
29     }

如果有更好的解決辦法請留言,大家一起學習,謝謝!!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM