Home > Back-end >  JS - Do async functions parameter references get affected by synchronous code execution?
JS - Do async functions parameter references get affected by synchronous code execution?

Time:09-27

Do async functions parameter references get affected by synchronous code execution?

To be more specific I am creating a little grid animation using an array of custom <Tile/>. Then in another function I am creating an array animation that holds "Keyframes" (I use the term loosely). Basically each index is an array of which <Tile/>s are changed in each "frame".

Then I have a Render function that takes that array of "keyframes" and renders them as follows:

// Returns a Promise that resolves after "ms" Milliseconds
const timer = (ms) => new Promise((res) => setTimeout(res, ms));

//Renders gameboard tile by tile with given ms delay
async function render(animation) {
  
  for (var i = 0; i < animation.length; i  ) {
    
    //do some rendering stuffs

    await timer(3000 / animation.length); // This *Should* ensure 3s of total animation time
  }
}

Now the question is if I were to add a "stopper" to this function in a way like:

//Renders gameboard tile by tile with given ms delay
async function render(animation, stop) {
  
  for (var i = 0; i < animation.length; i  ) {
    if(stop){
       //stop rendering
    }
    //do some rendering stuffs

    await timer(3000 / animation.length); // This *Should* ensure 3s of total animation time
  }
}

Lets say I call render multiple times.

If I were to create a synchronous way to change the value of stop to true: Would it then pause the asynchronous stack of render calls, update stop, then resume the render calls only to then exit because of the conditional? OR am I just mistaken and would the render calls simply not run at all because SOME kind of synchronous code would have to be executing in order to change the value of stop synchronously and in the scope of the async calls to render stop would HAVE to be false in order for the synchronous code to be finished and the async stack to start.

CodePudding user response:

Check for is stopped after promise of previous item is resolved.

let stopped = false;

function isStopped() {
  return stopped;
}

function stop() {
  stopped = true;
}

function renderItems(items) {
  return items.reduce((promise, item) => {
    return promise.then(() => {
      // Checks if stopped after each promis resolves in order
      if (!isStopped()) {
      // Run next render callback
      return asyncRenderItem(item);
    } else {
      // Dont run next
      return;
    }
    });

  }, Promise.resolve());
}

async function asyncRenderItem(item) { ... }
  • Related