jQuery无限的函数执行

bet*_*car 6 javascript jquery

我们想知道是否有可能有使用jQuery检查多个元素的功能,并根据通过点击分配给他们的类型,执行其他功能.基本上,一个功能将永远运行,而用户不刷新页面.

这个想法不是依赖事件点击来执行一个函数,而是依赖于分配给特定元素的类.

例如:

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

以上执行一次,我们需要一直运行.

Tom*_*lak 17

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

// ...repeat it once every second
window.setInterval(ganttEach, 1000);
Run Code Online (Sandbox Code Playgroud)

你不能"让它一直运行"(比如,在一个while(true)循环中),因为JavaScript是单线程的,阻塞线程意味着你的其他代码永远不会运行.setInterval()确保其他代码执行时存在必要的"空白".

setInterval()返回一个ID,您可以将其存储在变量中并clearInterval()在某个时刻输入以使其再次停止.


如果要确保函数的每个新迭代仅在前一个迭代完成之后才开始,请setTimeout()改为使用:

// 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();
Run Code Online (Sandbox Code Playgroud)

你可能应该包括一些方法来阻止无休止的重复,比如引入一个在setTimeout()调用之前检查过的标志.