简体   繁体   中英

How to make a loop do something during a certain time frame in JS

I'm pretty new to JavaScript so please keep that in mind when answering my question.

I'm trying to make something where it asks the user questions during a certain time frame. Questions are asked using the window.prompt() method. I have a do while loop going on in a function called askquestions() as you can see:

var randomNo1;
var randomNo2;
var time;

do {
  randomNo1 = Math.random() * 9;
  randomNo1 = Math.round(randomNo1);
  randomNo2 = Math.random() * 9;
  randomNo2 = Math.round(randomNo2);
  window.prompt("What is " + randomNo1 + " + " + randomNo2 + "?")
} while (time == 0);

How can I make it that time = 1 after 30 seconds? Thanks in advance for your help.

You can use:

document.setTimeout("str js code/func name call",millisec);
document.setTimeout("time=1;",30000);

to execute some js code once with delay

And for your specification the following method may be needed for other timing purposes:

document.setInterval("js code /func name call",millisec);

to execute at an interval

Besides,it is strongly not recommended to have a "waiting while" in your js code to provide some timing service, which may cause browser to take this thread as a not-responding thread

You could get the milliseconds since Jan 1 1970 using

date = new Date();
mil = date.getTime();

You do that at the beginning of your code for comparison, then get a more current one in the loop. If the time between the two is greater than some number of milliseconds, you can exit the loop ( while(curDate.getTime()-mil<30000) would be 30 seconds)

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