3

My main goal is to delay a counter before it triggers.

Imagine a timeout couting down 'n' to '0' and then fire an event, but it can be reset asyncly to 'n' every time something happens.

I tried to achieve this using 'promises' with $q.

I was trying to add dynamicly new promises with timeout inside chaining a brand new delay.

But before achieve this goal, i couldn't even chain new promises.

Example:

var d1 = $q.defer();
var d2 = $q.defer();

d1.promise.then(function(data) {
    return 'd1' + data;
});

d2.promise.then(function(data) {
    return 'd2' + data;                 
});

var t = $q.all([d1.promise]);

t.then(function(data) {
    console.log(data);
});

$timeout(function()
{
    d1.resolve("1000");
}, 1000);

$timeout(function()
{
    t.then(function() { 
        d2.resolve("800");
    });
}, 800);

It only outputs: ["1000"] instead of ["1000", "800"]

My search so far:

stackoverflow did not helped me.

angular-promise-tracker I can't understand this code, how it behaves is exactly for what I need. But it is made for something else.

Community
  • 1
  • 1
Ismael
  • 2,330
  • 1
  • 25
  • 37
  • `t` is only listening to `d1`, so you'll never get an array with both values. Both deferreds are being resolved though (if you add a console to `d2.promise.then`. angular-promise-tracker is creating wrapper promises and giving you an event listener. – kalley Aug 09 '13 at 15:38
  • 1
    would you accept an answer without promises? – d'alar'cop Aug 09 '13 at 15:42
  • @d'alar'cop I accepted because I solved the problem not using "promises". So, not-using-promises was the solution. Few lines of codes and gave me the same behavior. That's why. – Ismael Aug 09 '13 at 18:14
  • @d'alar'cop I did a Plunker preview just showing the behaviour working. Works fine, you need to open your console to see the console.log(). Now i can use as generic timer for anything, in my case, only validating some field after the user has stopped typing (just like an autocomplete). – Ismael Aug 09 '13 at 18:39
  • please note I am also the answerer :) I asked if you "would" before I answered (not "why"). – d'alar'cop Aug 09 '13 at 18:42
  • @d'alar'cop Sorry. I've just realized it but too late. No problem. – Ismael Aug 09 '13 at 19:09

1 Answers1

1

If you are willing to just use native javascript then this should work:

// create a handle to the timeout
var toHandle = window.setTimeout(X);

// put this in the event that causes a reset
window.clearTimeout(toHandle);
toHandle = window.setTimeout(X);

Where X is the function you want to occur on a delay. This also gives you the power to change the delay value as you wish.

Cheers.

d'alar'cop
  • 2,357
  • 1
  • 14
  • 18