jQuery无限的函数执行 [英] jQuery infinite function execution

查看:96
本文介绍了jQuery无限的函数执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

例如:

$("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.

推荐答案

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

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

你不能让它一直运行(比如, while(true) loop)因为JavaScript是单线程的并且阻塞线程意味着你的其他代码永远不会运行。 setInterval()确保其他代码有必要的空白。

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()返回一个可以存储在变量中的ID,并在某个时刻输入 clearInterval()以使其再次停止。

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

如果你想确保你的函数的每个新迭代只在之后的开始一个人真的完成了,使用 setTimeout()代替:

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();

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

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.

这篇关于jQuery无限的函数执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆