gpt4 book ai didi

javascript - jQuery无限函数执行

转载 作者:数据小太阳 更新时间:2023-10-29 04:55:05 24 4
gpt4 key购买 nike

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

这个想法不是依赖事件点击来执行功能,而是分配给特定元素的类。

例如:

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

上面只执行一次,我们需要一直运行。

最佳答案

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

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

你不能“让它一直运行”(比如,在 while(true) 循环中)因为 JavaScript 是单线程的,阻塞线程意味着你的其他 代码永远不会运行。 setInterval() 确保有必要的“间隙”供其他代码执行。

setInterval() 返回一个 ID,您可以将该 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();

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

关于javascript - jQuery无限函数执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3196647/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com