简体   繁体   English

JavaScript中的暂停功能

[英]Pausing function in javascript

I have a function which loops through rows in a table so that only one is shown at any given time. 我有一个循环遍历表中行的函数,以便在任何给定时间仅显示一个。

I want to expand on this so that when I hover over the table, it shows all the rows, and then when I move away, it resumes showing one row at a time. 我想对此进行扩展,以便当我将鼠标悬停在桌子上时,它显示所有行,然后当我离开时,它又恢复一次显示一行。

The Problem I have is that on hovering, the first function keeps going, is there a way to 'pause' the function. 我遇到的问题是,悬停时,第一个功能一直存在,有没有一种方法可以“暂停”该功能。 I've looked at various examples using ClearInterval(),but can't match them to my script. 我已经看过使用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();
        }
    ); 
}
);

Can anyone show me please how I can combine the two? 谁能告诉我如何将两者结合起来?

You need to keep track of the timer ID when you call setInterval : 调用setInterval时,您需要跟踪计时器ID:

var timerID;

function hideShow(time){
  timerID = setInterval(showRows, time);
}

Then later on when you want to stop the repetition, call clearInterval and pass in that ID: 然后,当您想停止重复时,调用clearInterval并传递该ID:

// ...
  $('.Group td').removeClass('RoundBottom');
  $('.Group').show();
  clearInterval(timerID);
},
function()
{
  hideShow(2000);
  $('.Group td').addClass('RoundBottom');
  // ...

You could just check the hovering state before doing anything else, like this: 您可以先检查悬停状态,然后再执行其他操作,如下所示:

function showRows() {
    if (isHovering) {
        return;
    }

    // ...
}

The isHovering variable is just a boolean with current hovering state, that could be set by your callback function. isHovering变量只是具有当前悬停状态的布尔值,可以由您的回调函数设置。

With the above approach, you can set your timer only once and forget about it. 使用上述方法,您只需设置一次计时器就可以了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM