我正在使用 angularjs (输入[数字])[ https://docs.angularjs.org/api/ng/input/input%5Bnumber%5D] 。在这里,我需要在几秒钟后自动触发一个 Action ,前提是在这几秒钟(比如 2 秒)内没有再进行任何数字更改。
在我的plunker example ,每次数字更改时都会调用该操作,但我需要仅当用户超过 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;
}
}
最佳答案
您需要的称为去抖动,这是一种非常知名的模式。
您可以使用 undercoreJs 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
关于javascript - 如果一段时间内没有对号码输入进行任何更改,则需要自动触发号码更改功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33368360/