javascript - 每次按键后终止 $timeout 并重置

标签 javascript angularjs

假设我有一些关于他们的 ng-models 的输入

<input type="text" ng-model="vm.man.name">
<input type="text" ng-model="vm.man.surName">

在我的 Controller 中,我有对象 vm.man={}; 。 我想做以下事情: 我想把 $watch 放在我的 vm.man 上, 所以如果我按 <input> 内的某个键,它应该等待 3 秒,然后向服务器发送响应。但是,如果我按下某个键,并在 3 秒内按下另一个键,它应该等待 3 秒,然后响应服务器。这是我已经完成的操作:

 $scope.$watch(()=>vm.man, function (newVal, oldVal) {
     if(angular.isUndefined(newVal)) {
         return console.log("newVal is Undefined")
     }else{
        vm.timer1= $timeout(function () {
         vm.someFunctionThatRespondsToServer();
         }, 3000);
     }
 }, true);

我现在遇到的问题是,它会在每次按键时产生响应。例如我按a在我的input它响应 a,然后我按 b它响应ab等等。 我想要得到这样的东西:我按 a如果没有其他按键,它会等待 3 秒,它会响应,或者我按了 a然后 2 秒后,假设我按了 b它等待 3 秒然后响应 ab如果 3 秒内没有其他按键按下。 提前致谢。

最佳答案

在 Angular 1/2 中,您可以使用 Lodash debounce 中的函数。这是链接和示例:https://lodash.com/docs/4.17.4#debounce

在 Angular 2 RC5 及更高版本中,您可以使用 debounceTime。 更多详情请点击此处 Angular and debounce

关于javascript - 每次按键后终止 $timeout 并重置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46532186/

相关文章:

javascript - jquery sum 从给定索引到 0 的点击表行

javascript - 样式表不适用于网页 MEAN 堆栈

css - 在 ionic slider 中从 sd 卡设置 div 背景图像

css - 如何在平均堆栈中设置 Caps Lock 警告气球

JavaScript(Angular)数组没有返回?

javascript - Bootstrap DatePicker - 将日期设置为明天

javascript - 未捕获的类型错误 : Cannot read property 'createIcon' of undefined when creating markers

javascript - 切换任何标签,就像 execCommand bold 对 b 所做的那样

javascript - if 语句显示 Angular 成功

angularjs - spring Boot 和 Angular JS : what is the best way to deal with the authentication?