jQuery/JS 点击时停止循环 setTimeout

我有一张地图,上面有多个城市。我还有一个循环显示每个城市的详细信息。一旦我点击其中一个城市,我想完全停止循环。


我尝试过:clearTimeout(loopIdx) 但它不起作用。请你帮助我好吗?!干杯。


环形:


$(function() {

 var $mapCol = $('.map-col');

 var $mapBtn = $('.map-btn');

 var $mapLoops = $('.map-loop');

 var $btnLoops = $('.btn-loop');

 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');


    setTimeout(function() {

     _loop((idx + 1) % $mapLoops.length);

        }, 6000);

     }(0));

});

BTN:


<div class="btn-loop">City</div>


慕田峪7331174
浏览 175回答 2
2回答

白板的微信

将 的结果分配setInterval()给变量,并在clearTimeout()调用中使用它。$(function() {&nbsp; var $mapCol = $('.map-col');&nbsp; var $mapBtn = $('.map-btn');&nbsp; var $mapLoops = $('.map-loop');&nbsp; var $btnLoops = $('.btn-loop');&nbsp; var timer;&nbsp; loopIdx = (function _loop(idx) {&nbsp; &nbsp; $mapCol.removeClass('active-map');&nbsp; &nbsp; $mapBtn.removeClass('active-btn');&nbsp; &nbsp; $mapLoops.removeClass('active-map').eq(idx).addClass('active-map');&nbsp; &nbsp; $btnLoops.removeClass('active-btn').eq(idx).addClass('active-btn');&nbsp; &nbsp; timer = setTimeout(function() {&nbsp; &nbsp; &nbsp; _loop((idx + 1) % $mapLoops.length);&nbsp; &nbsp; }, 2000);&nbsp; }(0));&nbsp; $btnLoops.click(function() {&nbsp; &nbsp; clearTimeout(timer);&nbsp; });});.map-loop.active-map {&nbsp; 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>

慕工程0101907

您需要通过名称或标识符访问 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); }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript