2 回答
TA贡献1883条经验 获得超3个赞
将 的结果分配setInterval()给变量,并在clearTimeout()调用中使用它。
$(function() {
var $mapCol = $('.map-col');
var $mapBtn = $('.map-btn');
var $mapLoops = $('.map-loop');
var $btnLoops = $('.btn-loop');
var timer;
loopIdx = (function _loop(idx) {
$mapCol.removeClass('active-map');
$mapBtn.removeClass('active-btn');
$mapLoops.removeClass('active-map').eq(idx).addClass('active-map');
$btnLoops.removeClass('active-btn').eq(idx).addClass('active-btn');
timer = setTimeout(function() {
_loop((idx + 1) % $mapLoops.length);
}, 2000);
}(0));
$btnLoops.click(function() {
clearTimeout(timer);
});
});
.map-loop.active-map {
background-color: yellow;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="btn-loop">City</div>
<div class="map-loop">1</div>
<div class="map-loop">2</div>
<div class="map-loop">3</div>
<div class="map-loop">4</div>
<div class="map-loop">5</div>
<div class="map-loop">6</div>
<div class="map-loop">7</div>
TA贡献1887条经验 获得超5个赞
您需要通过名称或标识符访问 timeoutID 来清除它。(请参阅https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/clearTimeout。)
如果你想loopIdx成为标识符,你可以使用类似的东西:
let needToClear = false;
let loopIdx = setTimeout(function(){}, 6000);
// ...state changes here...
if(needToClear){ clearTimeout(loopIdx); }
添加回答
举报