I am making a chess website and want to display an alert to tell the players who has won. However, when the alert is displayed, the last move made is not shown until the alert is closed. The alert function is last in the code, so it should appear after source for the images of the squares have been changed. How do I make the screen update before displaying the alert? I didn't have or find any ideas on how to fix this.
Asked
Active
Viewed 104 times
0
-
A naive solution would be putting the alert in a setTimeout. But you'd probably better creating your own modal, with your styles etc. – Gerardo Furtado Mar 08 '23 at 02:23
-
Welcome to SO. Please read through the https://stackoverflow.com/help/minimal-reproducible-example and include a minimal, complete, and reproducible example in your question. – Joshua Mar 08 '23 at 02:31
-
where is your code? – Antony Kao Mar 08 '23 at 03:02
-
Please provide enough code so others can better understand or reproduce the problem. – Community Mar 08 '23 at 06:49
-
There is a ` – Kaiido Mar 08 '23 at 06:59
1 Answers
0
The requestAnimationFrame()
function queues the callback to run immediately before rendering one frame. Once the browser starts working through the queue, all further calls to it count towards the frame after.
This means we can use it to essentially "wait" certain amounts of frames:
requestAnimationFrame(() => {
// This callback runs immediately before frame A
requestAnimationFrame(() => {
// This callback runs immediately before frame B; the frame after A
// ...
});
});
We can write a utility function for this:
function waitFrames(n, callback) {
if (n > 0) {
// After next frame, wait n-1 frames
requestAnimationFrame(() => waitFrames(n - 1, callback));
} else {
// Wait 0 frames; run before next frame
requestAnimationFrame(callback);
}
}
In your case, you'd want to wait for 1 frame.

Oskar Grosser
- 2,804
- 1
- 7
- 18
-
No need to wait for yet another frame, just queue a task after rAF fired (e.g with `setTimeout( ,0)`). – Kaiido Mar 08 '23 at 06:56
-
Thanks, but it does not seem to have an effect when I used it. I put the function in both `setTimeout(CheckGameOver(boardState),0)` and `waitFrames(CheckGameOver(boardState))` but neither of them fixed the issue, the alert still appeared before the screen updated. Same with when I tried `waitFrames(MovePiece)` (the function where the alert function is called), and `waitFrames(CheckGameOver)` (the function where the alert happens). Is there something I have done wrong when referencing the functions? – Jloom5 Mar 08 '23 at 23:31
-
@Jloom5 It seems you have not specified the amount of frames to wait for. The first argument should be a number that specifies how many frames to wait for. – Oskar Grosser Mar 08 '23 at 23:57
-
Isn't that what the variable n is for? I edited the code to set n inside the function for convenience. – Jloom5 Mar 09 '23 at 04:04