简体   繁体   中英

Settimeout in javascript performance issue

Problem

I am building algorithms simulator tool to simulate how algorithms work. In BFS Algorithm I wanted to slow down the result display

So I used setTimeout function after each step to wait about 10ms before hitting the next step. I used promise to be able to use async to easily wait the whole period and force the algorithm to stop till the wait function finishes

function implementation

function wait(time) {
    return new Promise(resolve => {
        setTimeout(() => {
            resolve();
        }, time);
    })
}

BFS

while (queue.length) {
    let currentId = queue[index++];
    let tile = board.tileOf(currentId);
    tile.visit();
    if (currentId == targetId) {
        return;
    }
    await wait(10);
    for (let direction of DIRECTIONS) {
        let childId = moveId(currentId, direction);
        if (childId == undefined)
            continue;
        childId = parseInt(childId);
        let child = board.tileOf(childId);
        if (child.available()) {
            child.visit(true);
            queue.push(childId);
            pervNode[childId] = currentId;
        }
    }
}

the problem is when I run the code it works fine but sometimes it takes very long time to display the solution more and more than just 10ms.

I am wondering why it's not accurate? is this because of the approach that I am using? and if there is a better solution what could it be?

Try the tool from here

As JavaScript is a single-thread language, when you place a function call inside setTimeout() , this function gets in a queue and waits until other functions in a call stack (that were called before it) are finished and the call stack become empty. Time you specify as a second parameter to setTimeout() starts counting from the moment of placing the function in the queue, but not always the queue is empty

i don't know the actual output but i think that could work

while (queue.length) {
  let currentId = queue[index++];
  let tile = board.tileOf(currentId);
  tile.visit();
  if (currentId == targetId) {
    return;
  }
  let timer;
  const loop = () => {
    for (let direction of DIRECTIONS) {
      let childId = moveId(currentId, direction);
      if (childId == undefined) continue;
      childId = parseInt(childId);
      let child = board.tileOf(childId);
      if (child.available()) {
        child.visit(true);
        queue.push(childId);
        pervNode[childId] = currentId;
      }
    }
  };
  const listener = () => {
    if (timer) {
      clearTimeout(timer);
    }
    timer = setTimeout(() => {
      loop();
    }, 100);
  };
  listener();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM