简体   繁体   中英

Break while loop with timer?

I was wondering is it possible to break a while loop with a timer? looked on the internet but could not find a solution for it.

while (true) {
  alert('hi');
} if (timer < 0) {
 timer?
 document.write('Time is up!');
 break;
}

Thank you.

You should use setTimeout for this.

 var timer = 3; setTimeout(excuteMethod, 1000); function excuteMethod() { alert(timer + ' call'); timer--; if (timer >= 0) setTimeout(excuteMethod, 1000); } 

Demo : http://jsfiddle.net/kishoresahas/9s9z7adt/

I'm not sure if this is the correct approach, but it works,

 (function() { var delay = 30; var date = new Date(); var timer = date.setTime(date.getTime() + delay); var count = 0; function validate() { var now = new Date(); if (+now > timer) return false; else return true; } while (true) { count++; console.log(count); if (!validate()) { console.log("Time expired"); break; } // Fail safe. if (count > 50000) { console.log("Count breached") break; } } })() 

You can change control value in timer function and break the loop.

var control = true;
while(control)
{
    ...
}

setTimeout(function(){
    control = false;
}, delay); //delay is miliseconds

Or based on counter

var control = true,
    counter = 10;

while(control){
    ...
}

// you can handle as count down
// count down counter every 1000 miliseconds
// after 10(counter start value) seconds
// change control value to false to break while loop
// and clear interval
var counterInterval = setInterval(function(){
    counter--;
    if(counter == 0)
    {
        control = false;
        clearInterval(counterInterval);
    }
},1000);

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