clearTimeout行为异常

clearTimeout behaving oddly

本文关键字:异常 clearTimeout      更新时间:2023-09-26

我正在处理一个模板文件,有3个列表项,当您滚动显示每个列表项的高亮文本时,加载隐藏的div将变为可见。鼠标悬停时,在div再次隐藏之前会设置一个延迟。clearTimeout用于用户是否在列出的项之间切换,以便加载新选择的div,并再次隐藏旧的div。我的剧本正在运作,这就是我需要帮助的原因。当你从底部项目向上滚动项目时,clearTimeout就像我希望的那样工作,但如果你从第一个项目向下滚动,它根本不会清除超时。

<script>function myClear1()
{
    clearTimeout(myFunction1, myFunction2, myFunction3);
    }
function myFunction1()
{
setTimeout(function(){document.getElementById('relatedproduct1').style.display = 'none';},500);
}
function myFunction2()
{
setTimeout(function(){document.getElementById('relatedproduct2').style.display = 'none';},500);
}
function myFunction3()
{
setTimeout(function(){document.getElementById('relatedproduct3').style.display = 'none';},500);
}
</script>

这些是脚本,下面我将在页面上使用它的地方添加代码。

<form class="relatedcheckboxes">
<input type="checkbox" class="relatedcheckboxes">
<div style="display:inline;cursor:pointer; color:#00F; background-color:#FFF;"onmouseover="document.getElementById('relatedproduct1').style.display = 'block'; document.getElementById('selectedProductsGroup').style.display ='none'; myClear1()"onmouseout="myFunction1()">Product Number:</div> Product Name - Sale Price
<br>
<input type="checkbox" name="Product Name" value="" class="relatedcheckboxes">
<div style="display:inline; cursor:pointer; color:#00F; background-color:#FFF;"onmouseover="document.getElementById('relatedproduct2').style.display = 'block';document.getElementById('selectedProductsGroup').style.display ='none';myClear1()"onmouseout="myFunction2()">Product Number</div>: Product Name - Sale Price
<br />
<input type="checkbox" name="Product Name" value="" class="relatedcheckboxes">
<div style="display:inline; cursor:pointer; color:#00F; background-color:#FFF;"onmouseover="document.getElementById('relatedproduct3').style.display = 'block';  myClear1()"onmouseout="myFunction3()">Product Number</div>: Product Name - Sale Price
</form>

必须将setTimeout的返回值传递给clearInterval,而不是函数。例如:

var timer = setTimeout(func, 1000);
clearTimeout(timer);

用最少的更改来调整你的代码是这样的:

var timer1;
function myClear1(){
    clearTimeout(timer1);
}
function myFunction1() {
    return setTimeout(function(){
        document.getElementById('relatedproduct1').style.display = 'none';
    },500);
}
<div onmouseover="myClear1()" onmouseout="timer1=myFunction1()">...</div>...