Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I'm making a webpage that you can edit the text and after you stop typing for 1 second it will automagically save what you've typed.

Currently i'm just working out the $timeout details. I have it working when I call the update method with no params, but when I call it with params, I get the error:

Error: fn is not a function $TimeoutProvider/this.$get</timeout/timeoutId<@http://localhost:63342/express_example/bower_components/angular/angular.js:14014 completeOutstandingRequest@http://localhost:63342/express_example/bower_components/angular/angular.js:4300 Browser/self.defer/timeoutId<@http://localhost:63342/express_example/bower_components/angular/angular.js:4601

Why am I getting this error when doing:

timeout = $timeout(update(element, content), 1000);

but not when I do:

timeout = $timeout(update, 1000);

Obviously I need to pass the params into the update method because I need to know what to update.

debounceUpdate($(this), data.content);

var debounceUpdate = function(element, content) {
    console.log('in debouce');
    if (timeout) {
      $timeout.cancel(timeout);
    }

    timeout = $timeout(update(element, content), 1000);
};

// Update an existing section
var update = function(element, content) {
    console.log('in update');
    console.log('section_id to update is '+element.data('sectionId'));
    console.log(content);
}
share|improve this question
    
pass the params into the update method - stackoverflow.com/questions/1190642/… –  Michal Stefanow Apr 30 '14 at 14:45

1 Answer 1

up vote 3 down vote accepted

Your code calls update immediately and tries to pass its return value as the $timeout callback. You really wanted to call update from the $timeout handler instead:

timeout = $timeout(function() {update(element, content);}, 1000);
share|improve this answer
    
Interesting.. Can you elaborate on this more? I understand callbacks in js, but I guess i'm not sure how your answer (which works) differs from what I had. –  Catfish Apr 30 '14 at 14:46
2  
update(element, content) calls update. Right away. So $timeout(update(element, content), 1000) calls update right away, then passes the return value of that as the first parameter to $timeout, which is also called right away. –  Dark Falcon Apr 30 '14 at 14:50
1  
function() {update(element, content);} creates a closure which, when invoked, calls update. $timeout(function() {update(element, content);}, 1000) calls $timeout right away and passes that closure as the first argument. $timeout waits a while, then invokes the closure, which invokes update. –  Dark Falcon Apr 30 '14 at 14:51

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.