James
James

Reputation: 53

Wait to execute until a function call comes to an end

When timeout() is called, it takes 100*100 ms to finish. (SUCCESS. NO NEED FOR FIX.)

When doThousandTimes() is called, it SHOULD take 1000*100*100 ms to finish. However, timeout() is called before the previous call finishes. I'm slow and have been failing at finding a solution to this. I'd appreciate any help.

var count = 0; // variables to hold random value and displacement
var i;
function stuff() {
  console.log("stuff");
}

function doThousandTimes() { //executes 1000 times
  while (count < 1000) {
    i = 0;
    timeout();
    count++;
  }
}

function timeout() { //executes 100 times
  setTimeout(function() {
    stuff();
    if (i < 100) {
      i++;
      timeout();
    }
  }, 100);
}
console.time("do1000");
doThousandTimes();
console.timeEnd("do1000");
console.time("timeout");
timeout();
console.timeEnd("timeout");

Upvotes: 0

Views: 68

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1075567

Nothing in your doThousandTimes waits for timeout to complete its series of timed callbacks. You can pass a callback into timeout that it calls when it's done with its series, so doThousandTimes can continue with the next, see comments:

var count = 0;
var i;
function stuff() {
  console.log("stuff: ", count, i);
}

function doThousandTimes(done) {
  if (count < 20) {
    // Update and call timeout, passing in a function
    // to use as its done callback that will
    // call doThousandTimes again
    count++;
    i = 0;
    // `bind` creates a function that will get done as an argument
    timeout(function() {
      doThousandTimes(done);
    });
  } else {
    // We're done -- call our done callback if any
    if (done) {
      done();
    }
  }
}

function timeout(done) {
  setTimeout(function() {
    stuff();
    if (i < 10) {
      i++;
      timeout(done);
    } else {
      // Done -- call our "done" callback, if any
      if (done) {
        done();
      }
    }
  }, 100);
}
// Note putting the `timeEnd`s and such *into* callbacks below
console.time("do1000");
doThousandTimes(function() {
  console.timeEnd("do1000");
  console.time("timeout");
  timeout(function() {
    console.timeEnd("timeout");
  });
});
.as-console-wrapper {
  max-height: 100% !important;
}

Note: I've changed the limits to count < 20 (rather than count < 1000) and i < 10 (rather than i < 100) just so the snippet can run to completion. I've also updated stuff to show the current count and i.

Upvotes: 1

Related Questions