I have a function that solves a puzzle in a browser. It might take a very long time to finish and I want to stop its execution if the runtime exceeds 30 seconds. Something like this:
function solve(puzzle) {
// A loop to solve a puzzle that might take minutes to run
while (notSolve){
keepFindingSolution(); // This is not a loop
}
return solution;
}
let solution = solve(veryHardPuzzle);
if (solution && solution.solved) {
// Do something
}
console.log("Other executions");
So, I don't want to block the UI thread when solving the function so that users can still interact with the website. I also want to get the solution from the solve(veryHardPuzzle)
once it's done, or break the execution of the function if the time is out.
I tried some different approaches below, but none of them work for me:
Wrap the solve()
function in setTimeout()
setTimeout(function () {
let solution = solve(veryHardPuzzle);
if (solution && solution.solved) {
// Do something
}
}, 30000);
console.log("Other executions");
This approach (from https://stackoverflow.com/a/26616321/6308776) doesn't block the UI thread, and the other executions are executed happily. However, it just basically waits 30 seconds before executing the inner solve(veryHardPuzzle)
function (please correct me if I'm wrong). If the solve(veryHardPuzzle)
function runs longer than 30 seconds then it would block the thread.
clearTimeout() once the solve()
is done
let timerId = setTimeout(function () {
let solution = solve(veryHardPuzzle);
clearTimeout(timerId);
if (solution && solution.solved) {
// Do something
}
}, 30000);
console.log("Other executions");
I thought that this would stop the timeout()
after the solution is found, but it technically waits 30 seconds before the solver(veryHardPuzzle)
is executed.
After doing some research, I realized setTimeout()
might not the thing I want. Do you have any ideas or techniques on how to solve this?