I'm making a loop with js.
Various processing is done in the loop.

If time is measured, the processing time in the loop is larger than the time interval of the loop.
(Loop time interval is 1 second, processing time in the loop is about 4 seconds)

Loop time interval cannot be changed.

I thought as follows.

var flg = 0;
$(function () {
  setInterval (function () {
  if (flg == 1) {continue;} ---------------------- (1)
  flg = 1;
  flg = 0;
  }, 1000);

When flg is 1, I want to make the loop idle without executing the process, and when flg is 0, I want to execute the process.

The above code does not do any processing.
(If i comment out the statement in (1), the process will be executed)

Can you tell me what's wrong?

  • Answer # 1

    In principle, JavaScript runs on a single thread.
    Therefore, the next loop will not be executed while executing the processing in the function given tosetInterval.
    As in the example of the question, if processing takes 4 seconds, the next time the function passed to setInterval is called is as soon as possible after 4 seconds.

    Thecontinuestatement can only be used within a for or while loop.
    In other words, the code you have provided is a syntax error, and the browser discards the following processing.

  • Answer # 2

    It is easiest to rewrite with setTimeout.

    【[Javascript] Difference in loop processing using setInterval and setTimeout-03LOG】

    Is it enough to make a judgment based on whether or not 1000 ms has passed since

    orflgis filled with the processing end time?

Related articles