How To Pause Javascript For Loop (animating Bubble Sort)?
Solution 1:
I'm going to assume you're doing this on a browser. You need to yield back to the event loop in order for other things to happen, such as repainting the page. Probably the simplest thing is to make your bubbleSort
an async
method and have it await
something, such as a timer callback:
asyncbubbleSort() { // <=== Note the `async`let solved = false;
while (!solved) {
let swaps = 0;
// *** No `setInterval`for (const [index, item] of this.items.entries()) {
if (index > 0) {
const result = compare(this.items[index - 1], item);
if (result) { // *** Did it do something?
swaps += result;
await delay(0); // *** Wait for it to be redrawn
}
}
});
if (swaps === 0) {
solved = true;
}
}
}
...where delay
might be:
functiondelay(ms) {
returnnewPromise(resolve =>setTimeout(resolve, ms));
}
When you call bubbleSort
, it will return a promise almost immediately, and continue its logic asynchronously until it's done, then settle the promise.
Note that async
functions were added in ES2018. The're well-supported by modern browsers, but you may need a tool like Babel to transpile for older ones.
If you want to be even more precise, you could use requestAnimationFrame
rather than setTimeout
with a zero-length timeout. Here's a somewhat counter-intuitive function for that:
constnextFrame = (cb = () => {}) => newPromise(resolve => {
requestAnimationFrame(() => {
cb();
resolve();
});
});
...which you'd use in place of delay
:
await nextFrame();
(In your case, you don't need to pass any callback, the default do-nothing callback is sufficient.)
I explain the reason for the odd design of that function in this tweet (which in turn is asking whether it really needs to be designed that oddly).
Another approach is to invert your logic a bit and use a generator function that generates each swap. Then you can drive that generator in a loop. That's the approach I used when answering this other question about visualizing buble sort.
Post a Comment for "How To Pause Javascript For Loop (animating Bubble Sort)?"