-1

There are two issues with my script: It doesn't update random every new round and keeps running forever. But in my opinion it should do both .. How can I make the loop recognize that this.short has changed?

while ( ! this.short) {
    random = Math.random().toString(36).substring(2,7).toUpperCase();

    dpd.links.get({short: random}, function(res, err) {
        if (err)
            cancel('Error', 500);

        if ( ! res.length)
            this.short = random;
    });
}
zimt28
  • 705
  • 2
  • 7
  • 20

1 Answers1

1

Math.random() actually returns a pseudo-random number seeded from the current time. So it's not surprising that it doesn't update for every loop.

As for this.short: this always refers to the “owner” of the current function. So the this in this.short = random is probably different from the this in your while loop. What you need to do is assign this to a variable first. For example:

var current = this;
while (!current.short) {
    ...
    current.short = random;
}
Christophe
  • 27,383
  • 28
  • 97
  • 140
  • Thanks, I'll use something different there. But the script still doesn't stop the loop – zimt28 Aug 08 '13 at 17:29
  • where/when would you expect the loop to stop? if !this.short and res.length are true, the loop will run forever. – Christophe Aug 08 '13 at 17:37
  • Line 9 should do it. I'm waiting for a random which gives me a result.length of 0 and right then it should stop – zimt28 Aug 08 '13 at 17:44
  • Well, if random is not updated (cf. my answer) then why should result.length change? – Christophe Aug 08 '13 at 17:54
  • I've updated the random function and it still keeps running. As the db is empty at the moment any first result should have the result.length of 0. If I change this.short outside my closure the loop seems to get the difference, interestingly. – zimt28 Aug 08 '13 at 18:07