繁体   English   中英

如何运行暂停和停止setInterval

[英]How to run pause and stop setInterval

我的任务:

  1. 悬停当前块时运行setInterval循环,例如#main

  2. 当我将鼠标悬停在#main的某些子元素上时,必须暂停setInterval

  3. 当我离开#main的儿童元素,并返回我的鼠标重心转回#main后setTimeOut应该再次运行。 这是屏幕http://joxi.ru/L215V3qh65weW2


我的代码:

let num = 0;
var timer = function() { // auto click
    { num >= $(`.the_wrap_graf`).children().length-1 ? num = 0 : num++ }
    $(`.year-wrap:eq(${num}) .q`).click()
}

var timerID = null // name of interval

$('.the_wrap_feed').hover(function (ev) { // hover run loop #main
    timerID = setInterval(timer, 3000);
}, function (ev) { // mouseleave kill loop
    clearInterval(timerID)
})

$(`.q`).mouseenter(function(e) { // kill loop when hover square
    clearInterval(timerID)
})

如果我将回调添加到$(. .q ),它将崩溃。 我该怎么做?

您不能暂停间隔计时器。 您只能取消它并重新开始。

重新要求,我想我可能会使用mouseentermouseleave (已经使用hover )并跟踪光标是在#main还是在子级中:

 var timer = 0; var timerValue = 0; var inMain = 0; var inChild = 0; function showTimer() { $("#timer").text( timer ? "Running: " + timerValue : "Not running" ); } function updateTimer() { if (inMain && !inChild) { if (!timer) { timer = setInterval(tick, 100); } } else { if (timer) { clearInterval(timer); timer = 0; } } } function tick() { ++timerValue; showTimer(); } showTimer(); $("#main") .hover( function() { ++inMain; updateTimer(); }, function() { --inMain; updateTimer(); } ); $("#main .child") .hover( function() { ++inChild; updateTimer(); }, function() { --inChild; updateTimer(); } ); 
 #main { border: 1px solid #aaa; padding: 8px; } .child { border: 1px solid #ddd; margin: 8px; } 
 <div id="timer"></div> <div> Not in main <div id="main"> In main, not in any children <div class="child">one child</div> <div class="child">another child</div> </div> </div> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> 

暂无
暂无

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

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