Javascript:无法清除超时

爱默生

我试图在用户停止键入后的短暂延迟后调用一个函数,但clearTimeout()似乎并没有按照我的想法去做。以下是Angular JS控制器中的内容。

$scope.typing = false;
$scope.delay = undefined;

//Triggered by ng-keydown...
$scope.startTyping = function() {
    $scope.typing = true;
            console.log('start1', $scope.delay); //6
    clearTimeout( $scope.delay );
            console.log('start2', $scope.delay); //6... NOT getting cleared!
}

//Triggered by ng-keyup...
$scope.stopTyping = function() {
    $scope.typing = false;
    $scope.delay = setTimeout( $scope.lookup, 1000);
}

$scope.lookup = function() {

    if ($scope.typing === true){
        return false;
    }
    console.log('lookup'); //This fires after every key!

lookup在日志中看到了每个键,而不是每次延迟之后。为什么是这样?

更新

在记录了delay的值之后,很明显clearTimeout()没有重置计时器,而是设置了多个计时器,每个计时器都触发了查找功能。

以供参考...

对于其他任何进行故障排除的人clearTimeout(),这里有一些类似的问题可以解决您的问题(但不能解决我的问题):

clearTimeout不起作用

clearTimeout()无法正常工作

clearTimeout无法正常工作

clearTimeout不起作用

昏迷

http://jsfiddle.net/coma/y52Q2/1/

控制器

app.controller('Main', function ($scope) {

    var delay;

    var lookup = function() {

        console.log($scope.input);
    };

    $scope.lookup = function() {

        clearTimeout(delay);
        delay = setTimeout(lookup, 1000);
    };
});

看法

<div ng-controller="Main">
    <input ng-model="input" ng-change="lookup()"/>
</div>

上/下尝试stopTyping时间的问题是被调用的次数比startTyping

http://jsfiddle.net/coma/5hFjY/1/

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章