星期五, 2月 06, 2015

[Angular] ng-src造成的infinite loop

目前在介面上顯示圖片列表時,因為圖片的網址加了random的參數來解決cache的議題,
但會產生infinite loop的error,打開console可以看到。
找到了Stackoverflow以下解譯這個的原因。

http://stackoverflow.com/questions/17222526/angular-js-in-ng-src-causes-infinite-loop
Well I think the problem is the getRandom function returning a different value every time it's called. Here's what happens:
  1. Angular call your function
  2. Gets the value
  3. See's it's different from the previous value
  4. Marks the cycle as dirty
  5. After the cycle is finished it re-runs the cycle thus getting a new value ...
The idea would be to have getRandom give discreet values over a period of time. For example only give a new value every 1, 10, 30 sec whatever you see fit.
This advice applies to many things, actually. Angular provides no guarantees about how many times it will call your functions that are found in bindings. So you need to make them fast and also you need to make sure that for the same input they return the same output(most times, though in this case it might be justified).
Also consider exactly when/how the image might change and if the actual changes can be triggered by something else consider only creating a new result value for getRandom only when the actual changes are triggered(ex: user uploads a new profile image, a timer executes, etc)
UPDATE: Can't replicate it in plunker using Chrome

解決的方法可以利用一個timer來透過記錄上一次變更的時間差來避免一直檢查的問題。




$scope.lastMillis = new Date().getTime();
     $scope.getRandom=function(){
         var curMillis = new Date().getTime();
         if (curMillis-$scope.lastMillis>5000) {
             $scope.lastMillis = curMillis;
         }
         return $scope.lastMillis;
     };

沒有留言:

張貼留言

留個話吧:)

其他你感興趣的文章

Related Posts with Thumbnails