2016-12-22 28 views
0

我在學習Angular JS 1時正在進行一些測試。我有一些文本區域在用戶進入和退出時通過Angular函數顯示一些文本。 enter函數等待3秒鐘,退出函數等待5秒鐘。這工作到目前爲止。在AngularJS中停止計時函數1

該任務的下一部分是如果用戶不等待超時數量,則取消將文本綁定到文本區域的功能。我很困惑,但我認爲我需要使用承諾。

var myApp = angular.module('myApp', []); 

function checkTimeout() { 
    console.log("Timeout is working..."); 
} 

myApp.filter('rawHtml', ['$sce', function($sce){ 
    return function(val) { 
    return $sce.trustAsHtml(val); 
    }; 
}]) 

myApp.controller("MyCtrl", function($scope, $timeout){ 

$timeout(checkTimeout, 3000); 

$scope.data = [{ 
    "id": 1, 
    "act": "" 
}, { 
    "id": 2, 
    "act": "" 
}, { 
    "id": 3, 
    "act": "" 
}, { 
    "id": 4, 
    "act": "" 
}, { 
    "id": 5, 
    "act": "" 
}, { 
    "id": 6, 
    "act": "" 
}, { 
    "id": 7, 
    "act": "" 
}, { 
    "id": 8, 
    "act": "" 
}, { 
    "id": 9, 
    "act": "" 
}]; 

$scope.enter1 = function(num) { 
    $timeout (function(){num.act = " - enter";}, 3000); 
} 

$scope.exit1 = function(num) { 
    $timeout (function(){num.act = " - exit";}, 5000); 
} 


}) 

HTML:

<body ng-app="myApp"> 
    <div ng-controller="MyCtrl" style="width:100%;margin:10px;"> 
     <p>How can I stop the functions enter1 and exit1 from binding text to the textarea if the user does not wait the 3 seconds (enter1) and 5 seconds (exit1) for them to execute?</p> 
     <div style="float:right; width:49%;"> 
     <div ng-repeat="num in data" style="margin:3px;"> 
      <textarea ng-focus="enter1(num)" ng-blur="exit1(num)">{{ num.id }}{{ num.act }}</textarea> 
     </div> 
     </div> 
    </div> 
</body> 

這裏的小提琴:https://jsfiddle.net/mediaguru/q3qt5frk/

回答

2

$timeout構造函數返回一個值,可用於訪問計時器。

var myTimer = $timeout(checkTimeout, 3000); 

//Kill it 
$timeout.cancel (myTimer); 
+0

感謝Dominic的迴應。所以在你的例子中,如果它發生在3000ms內,我將如何與$ timeout.cancel模糊?希望這並不太清楚。 – mediaguru

+0

基本上,每當你啓動一個計時器,就把它存儲在一個變量中。如果您需要提前結束計時器,請在變量上調用$ timeout.cancel。否則,讓它運行並忽略它。我會添加更多的上下文,但我不確定我瞭解您的問題。 –

+0

讓我們只是採取焦點功能。用戶在該字段中標籤或點擊。如果用戶在現場停留3秒或更長時間,則字段中會顯示「enter」字樣。如果用戶在3秒前離開該字段,則不會出現Enter字樣。 – mediaguru

0

您必須清除所有計時器。否則,內存泄漏將在那裏。清除定時器,如果調用定時器的元素被銷燬。在角度上,每個元素都有範圍。如果特定元素的範圍被摧毀,我們必須清除所有計時器和事件,則會觸發$scope.$destroy()

var timers = new Array(); 
... 
// add a timer to the array 
timers.push(setTimeout('someFunc()', 1000)); 
... 
// clear all timers in the array 
for (var i = 0; i < timers.length; i++) 
{ 
    clearTimeout(timers[i]); 
}