Javascript: failed clearTimeout

I'm trying to call a function after a short delay after the user stops typing, but clearTimeout()doesn't seem to do what I think. Inside the Angular JS controller is the following.

$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 lookupin the logs for each key, and not after each delay. Why is this?

Update

After registering the value, delayit is clear that it clearTimeout()does not reset the timer, and instead, several timers are set, and each of them starts the search function.

For reference...

For anyone else troubleshooting clearTimeout(), here are some similar questions that might solve your problem (but not mine):

clearTimeout not working

clearTimeout () does not work

clearTimeout not working

clearTimeout not working

+4
2

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>

attimp / , stopTyping , startTyping:

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

+3

: 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();
+1

All Articles