0

Is there a way to use only one instance of Angulars $timeout?

For example, there is this code:

for(i=0; i<10; i++) {
    $timeout(function() {
        console.log('test');
    }, 2000);
}

Evaluating this code, angular will return 10 console messages after 2 seconds. Is there a way to get only one last message?

EDIT: Loop is an example, I dont know the number of cycles, I just need the last one.

Thanks

1 Answer 1

1

I think you mean that everythime a new message is set, you only have to use that timeout?

var timeout;
for (var i = 0; i < 10; i++) {
    if (timeout)
        timeout.cancel();

    timeout = $timeout(function() {
        console.log("test");
    }, 2000);
}

Or, if you just need to do someting on the last one of the loop:

var someLength = 83;
for (var i = 0; i < someLength; i++) {
    if (i === someLength - 1) {
        $timeout(function() {
            console.log("test");
        }, 2000);
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Yes, its the first one. Trying to implement now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.