Back

要优雅/正确的使用 setTimeout!

发布时间: 2016-08-27 01:40:00

setTimeout 是 javascript的经典方法. 

作用是让一段代码延后 xx ms 执行. 

但是, 使用它要有几个前提:

1. 你的思路是明确的. 不要弄迷糊

2. 不要替代 sucess  这样的 callback 函数. 

例如, 下面的代码, 就是非常错误的用法:  

正确的使用set Timeout

它会直接导致 价格算不出来: 

如下图:

Wrong Settimeout

修改后的代码: 

        // 把 定义的 上级scope 的变量拿过来. 
        var that = this
        var fee 
        this.$http.get(this.$config.API + '/interface/shoppings/product_details', {product_id: this.order.shopping_product_id}).then(function (response) {
          this.$set('product', response.data.product)
          // 把 原来在setTimeout中的代码, 放到这个 success callback 函数中来.
          fee = that.fee
          console.info("== product.price: " + that.product.price)
          console.info("== order.buy_counts: " + that.order.buy_counts)
          var f = parseFloat(that.product.price) * parseInt(that.order.buy_counts)
          that.$set('fee', f)
        }, function (response) {
          this.showAlert(response.data.error)
        })  
 
        // 原有的 一些逻辑, 跟 callback无关的, 保持不变. 
        setTimeout(function () {
          window.fit_mobile_function()
          console.info('-- show --')
          $('#main').show()
        }, 200)

上面的代码运行后, 就正确了: 

Screenshot From 2016 08 27 09 53 29

Back