'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



Solution 1:[1]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 coder