简体   繁体   中英

How can one reset one variable in Javascript and playing an alert after a specific time?

I am trying to program a little game that should reload after 5 seconds and tell people that they were too slow. Moreover, the variable points should be reset, so that they can start from new. With

 setInterval(function(){
                window.location.href = "javascript:window.top.location.reload(true)";
            }, 5000);    

the whole website is loaded and people have to begin from scratch. The same happens when they press command+R.

I tried now to reset the variable points and show the alert that they were too slow.

 setInterval(function(){
                alert("You were too slow!");
                 points = 0; 
            }, 5000);

If I use this code, then the alert keeps on popping up very quickly. How can I reset everything and only get the alert every 5 seconds?

Depending on the browser the internal timer will continue running while the modal is displayed like in Firefox, or freez like in Chrome. So in Firefox if the modal stays open longer then 5 seconds, then the next one will be showed immediatily after the current one is closed.

There are only rare cases where you really want to use setInterval even if you have events that happen in regular intervals you most of the time should use setTimeout instead.

var roundTimeoutTimer;

function tookToLong() {
   alert("You were too slow!");
   points = 0; 
}

function startTask() {
   roundTimeoutTimer = setTimeout(tookToLong, 5000)
}

function finishedTask() {
   clearTimeout(roundTimeoutTimer)
}

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