I'm making a chess website and want to display an alert to tell players who won. However, when the alert is displayed, the last movement is not displayed until the alert is turned off. The alert function is at the end of the code, so it should appear after the source of the block image changes. How can I update the screen before showing the alert? I don't have or found any ideas on how to solve this problem.
P粉2835590332024-03-31 16:22:38
requestAnimationFrame()
FunctionQueue a callback to run immediately before rendering a frame. Once the browser starts processing the queue, all further calls to it will count after frames.
This means we can use this to "wait" for a certain number 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 need to wait 1 frame.