سؤال

I'm trying to call a function after a short delay after a user stops typing, but clearTimeout() does not seem to be doing what I think. The following is inside an Angular JS controller.

$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!

I see lookup in the logs for every key, instead of after every delay. Why is this?

Update

After logging the value of delay it is clear that clearTimeout() is not reseting the timer and instead, multiple timers are getting set and each one is triggering the lookup function.

For reference...

For anyone else troubleshooting clearTimeout(), here are some similar questions that may solve your problem (but didn't solve mine):

clearTimeout not working

clearTimeout() not working

clearTimeout is not working

clearTimeout not working

هل كانت مفيدة؟

المحلول

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

Controller

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

    var delay;

    var lookup = function() {

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

    $scope.lookup = function() {

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

View

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

The problem with the up/down attemp is that stopTyping gets called more times than startTyping:

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

نصائح أخرى

I would do like this : http://jsfiddle.net/TN6zA/2/

$scope = {};

    //on keydown...
    document.getElementById("foo").onkeydown = function() {    
        clearTimeout( $scope.delay );
        $scope.delay = setTimeout( $scope.lookup, 1000);
        document.getElementById("myDiv").innerHTML = "Someone is typing";
    }

    $scope.lookup = function() {
        document.getElementById("myDiv").innerHTML = "Nobody is typing";
    }

    $scope.lookup();
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top