Я использую angularjs (input [number]) [ https://docs.angularjs.org/api/ng/input/input%5Bnumber%5D]. В этом случае мне нужно трижды активировать действие через несколько секунд, только если за эти несколько секунд не было сделано никаких изменений количества, скажем, 2 секунды.
В моем примере plunker действие вызывается каждый раз, когда число изменяется, но вместо этого мне нужно, чтобы действие было запущено только тогда, когда пользователь не изменил значение более чем на 2 секунды.
<div class="col-md-3 divGridText">
<label for="excludeMinutesStep" style="font-weight:bold">Exclude tasks < </label>
<input id="excludeMinutesStep" min="0" max="10" ng-model="excludeValue" ng-change="numericStepperChanged(excludeValue)" size="2" style="width:40px;" type="number" /> <b>minutes</b>
</div>
$scope.excludeValue = 5;
$scope.numericStepperInitValue = 0;
$scope.numericStepperChanged = function(data) {console.log("A");
$scope.numericStepperHit = true;
if (data != undefined) {
$scope.excludeValue = data;
if (data == 0) {
$scope.isExcludeNeeded = false;
}
if ($scope.numericStepperInitValue == 0) {
$timeout($scope.callAtNumercStepperChangeTimeout, 2000);
}
}
}
$scope.callAtNumercStepperChangeTimeout = function() {
$scope.numericStepperHit = false;
$scope.numericStepperInitValue++;
$scope.changeGraph();
}
$scope.changeGraph = function() {
if (!$scope.numericStepperHit) {
console.log("Action called "+$scope.excludeValue);
$scope.mytext = "Action called "+$scope.excludeValue;
$scope.isExcludeNeeded = true;
}
}
То, что вам нужно, называется debouncing, и это очень хорошо известный шаблон.
Вы можете использовать debcore js debounce:
$scope.debouncedFunction = _.debounce(myFunction, 2000);
<input ng-change="debouncedFunction()" size="2" style="width:40px;" type="number" />
Или вы можете реализовать его самостоятельно. Что-то вроде этого:
var promise = null;
function debouncedFcn{
if(promise)
$timeout.cancel(promise);
var promise = $timeout(myFunction, 2000);
}
Ссылка: Debounce
Я сделал функцию с именем timer, которая проверяет, изменилось ли значение за 2 секунды. Если не срабатывает mainFunction(), который вызывает предупреждение. И используется функция таймера в $ scope. $ Watch, которая следит за изменением excludeValue
$scope.excludeValue = 5;
$scope.$watch('excludeValue',function(oldVal,newVal){
if(oldVal !== newVal) // a new change
{
timer(oldVal,newVal)
}
});
var timer = function(oldVal,newVal){
var currentVal = angular.copy($scope.excludeValue);
$timeout(function(){
if(currentVal == $scope.excludeValue)
{
// there is no change made in 2 sec
mainFunction()
}
else
{
// change made in 2 sec
}
}, 2000);
};
timer();
var mainFunction = function(){
alert('No change made in 2 sec.');
};
вот мой плункер
oldVal
и newVal
в функции таймера?