Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery infinite function execution

We want to know if it is possible to have a function using jQuery to inspect a number of elements and, depending on the types assigned to them by one click, perform other functions. Basically, a function that would run forever, while the user does not refresh the page.

The idea is not to depend on events clicks to perform a function, but the classes assigned to a specific element.

For example:

$("td.gantt").each(function() {
    if($(this).hasClass("oper")) {
       //execute a serie of functions
    }
    if($(this).hasClass("preop")) {
      //execute a serie of functions
    }
});

The above is executed once, and we need to run all the time.

like image 980
betacar Avatar asked Jul 07 '10 16:07

betacar


2 Answers

// define a function...
function ganttEach() {
  $("td.gantt").each(function() {
    // ...
  });
}

// ...repeat it once every second
window.setInterval(ganttEach, 1000);

You can't "let it run all the time" (like, in a while(true) loop) because JavaScript is single-threaded and blocking the thread means your other code will never run. setInterval() makes sure there are necessary "gaps" for other code to execute.

setInterval() returns an ID that you can store in a variable and feed to clearInterval() at some point to make it stop again.


If you want to make sure that every new iteration of your function starts only after the previous one has really finished, use setTimeout() instead:

// define a self-repeating function...
function ganttEach() {
  $("td.gantt").each(function() {
    // ...
  });
  window.setTimeout(ganttEach, 1000); // calls itself again in one second
}

// ...initiate self-repeating function
ganttEach();

You should probably include some way to stop the endless repetition here as well, like introducing a flag that's checked before the setTimeout() call.

like image 194
Tomalak Avatar answered Nov 04 '22 21:11

Tomalak


You can run your check every few milliseconds, say 50ms, using setInterval

window.setInterval (function () { 
  // do checks here
}, 50);

You might end up using a lot of CPU power if your checks are too frequent, or too complicated.

like image 40
Tim Rogers Avatar answered Nov 04 '22 22:11

Tim Rogers