简体   繁体   中英

How to reload page in javascript after an alert in Chrome

I'm running through the MDN canvas game tutorial of the game Breakout. When the ball passes the paddle, the game should end and the page reload, starting again.

The code looks like this:

 if (y + dy < ballRadius) {
     dy = -dy;
 } else if(y + dy > canvas.height-ballRadius) {
     if(x > paddleX && x < paddleX + paddleWidth) {
        dy = -dy;
     } else {
        alert("GAME OVER");
        document.location.reload();
     }
 }

In FireFox and Safari this runs as expected, after dismissing the alert, the page reloads and the script starts over from beginning.

However, in Chrome, after the the ball hits the end of the y bounds of the canvas and the alert is displayed, if you hit Ok to dismiss it, the page does not appear to reload. Instead, the ball continues to move and after every iteration, a new alert is displayed (which if you dismiss with Ok it continues without reload).

Anyone have any idea what's happening and why the page will not reload?

Here's the full code

The same functionality as in Chrome can be observed in JSFiddle

Update: In the console in Chrome, if I try document.location.reload() I get undefined . document.location results in localhost as expected.

Clear the interval after you call the reload.

Change setInterval(draw, 10); to var interval = setInterval(draw, 10); .

Add clearInterval(interval); after document.location.reload(); .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM