Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Waiting for functions to complete in JavaScript

Waiting for functions to complete in JavaScript

Problem

How come the following code, generates a different output everytime (not because of the random function) but it gives undefined for some values, sometimes some others. What is the problem?

function getRandom(ubound) {
  return Math.floor((Math.random()*10) % ubound); 
}

function getInterval() {
  var interval = [getRandom(10), getRandom(10)];
  if(interval[1] >= interval[0])
    return interval;
  else
    getInterval();
}

function generateIntervals() {
  for(var i = 0; i 

I get outputs like:

Node 1: 0,9
Node 2: 0,3
Node 3: undefined
Node 4: 2,2

or

Node 1: 3,3
Node 2: 3,3
Node 3: 1,8
Node 4: undefined
Problem courtesy of: Sankha Narayan Guria

Solution

Missing a return in your recursive function:

if(interval[1] >= interval[0])
    return interval;
else
    return getInterval();
//  ^^^^^^

Though I'd personally just swap the 2 values around instead of using recursion for that. =]

if(interval[1] >= interval[0])
    return interval;
else
    return [interval[1], interval[0]];

Or more simply/semantic using Array.reverse():

if(interval[1] 

Fiddle

Solution courtesy of: Fabrício Matté

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Waiting for functions to complete in JavaScript

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×