[英]Pausing function in javascript
我有一个循环遍历表中行的函数,以便在任何给定时间仅显示一个。
我想对此进行扩展,以便当我将鼠标悬停在桌子上时,它显示所有行,然后当我离开时,它又恢复一次显示一行。
我遇到的问题是,悬停时,第一个功能一直存在,有没有一种方法可以“暂停”该功能。 我已经看过使用ClearInterval()的各种示例,但是无法将它们与我的脚本匹配。
//Calling The function that loops through the rows
function hideShow(time)
{
setInterval('showRows()',time);
};
//Set the time between each 'loop' and start looping
$(document).ready(function()
{
hideShow(2000);
}
);
//The hover function to show / hide all the rows
$(document).ready(function()
{
$('#dbTable1 tr').hover(function()
{
$('.Group td').removeClass('RoundBottom');
$('.Group').show();
},
function()
{
$('.Group td').addClass('RoundBottom');
$('.Group').hide();
}
);
}
);
谁能告诉我如何将两者结合起来?
调用setInterval
时,您需要跟踪计时器ID:
var timerID;
function hideShow(time){
timerID = setInterval(showRows, time);
}
然后,当您想停止重复时,调用clearInterval
并传递该ID:
// ...
$('.Group td').removeClass('RoundBottom');
$('.Group').show();
clearInterval(timerID);
},
function()
{
hideShow(2000);
$('.Group td').addClass('RoundBottom');
// ...
您可以先检查悬停状态,然后再执行其他操作,如下所示:
function showRows() {
if (isHovering) {
return;
}
// ...
}
isHovering
变量只是具有当前悬停状态的布尔值,可以由您的回调函数设置。
使用上述方法,您只需设置一次计时器就可以了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.