【问题标题】:setInterval executions too fastsetInterval 执行太快
【发布时间】:2016-09-30 04:57:23
【问题描述】:

在他们自己的案例之后有很多关于这个问题的好帖子,但我在我的案例中找不到任何好的答案。

我在不同的文件中有多个 setInterval,它们各自发挥作用:

  1. 该应用程序是一个幻灯片目录,我有一个主要的setInterval,它处理主应用程序中自定义幻灯片的循环。

    mainInterval = setInterval(changeSlide, 20000); execute after 20 seconds
    
    function changeSlide(){
       // .... do changes
    }
    
  2. 另一个用作空闲计时器,当客户单击幻灯片的信息时,会出现模态框,但当没有用户交互时,模态框将关闭。此函数驻留在另一个 javascripts 文件中。

    $('.item').click(function(e){
        // .. show modal
    
         idleInterval = setInterval(timerIncrement, 1000); // executes every 1 secs.
    });
    
    // This will reset idleTime when user interact with mousemove
    $(this).mousemove(function (e) {
        idleTime = 0;
    });
    
    // This will reset idleTime when user interact with keypress.
    // Since there is a side panel search engine will appear 
    // when a button search is clicked.
    $(this).keypress(function (e) {
        idleTime = 0;
    });
    
    
    function timerIncrement() {
        idleTime = idleTime + 1; // increment whenever the function is called
    
        // idleTime is more than 10 secs?
        // If true (10 secs is met) close the search panel if open
        //  and close the modal.
        if (idleTime > 10) {  
    
            // ... close the search panel if open
            // ... hides modal
    
            clearInterval(idleInterval);
        }
    }
    

更新

因为有一个modal会在.item被点击的时候显示,为了避免多次setInterval。

当触发模态隐藏事件时,我处理clearInterval(IdleInterval)

$('#item-modal').on('hide.uk.modal', function(e){
    clearInterval(idleInterval);
});

现在最大的问题是模式在实际 10 秒之前关闭,当我打印 console.log(idleTime); bang!我看到计时器的执行速度比平时快。

【问题讨论】:

  • 您是否点击了多次?如果单击两次,多个计时器调度程序会同时运行,每个调度程序都会递增相同的全局变量。
  • 哦,当模态隐藏时有clearInterval(idleInterval) 来处理这个问题。我会更新问题更多
  • 我宁愿使用setInterval(function(){ // do something },1000);
  • 如果您嵌套了item,也会创建多个间隔。如果没有重现这个的演示,没有人可以提供帮助......我们所能做的就是猜测
  • 你能解释一下setInterval(my_defined_func, 10000);setInterval(function(){ // do something },1000);之间的区别

标签: javascript jquery


【解决方案1】:

您没有在每次单击 .item 时重置间隔,这可能导致运行多个间隔时出现问题

// explicitely save the state you will be modifying to the window
var idleInterval = null
var idleTime = 0

$('.item').click(function(e) {
  // clear the interval if it's set
  clearInterval(idleInterval)
  idleInterval = setInterval(timerIncrement, 1000);
});

var resetIdleTime = function(e) {
  idleTime = 0;
}
$(this)
  .mousemove(resetIdleTime)
  .keypress(resetIdleTime);

function timerIncrement() {
  idleTime = idleTime + 1;
  console.log(idleTime)
  if (idleTime > 2) {
    alert('show modal')
    clearInterval(idleInterval);
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="item">this is the item</div>

【讨论】:

    猜你喜欢
    • 2014-02-01
    • 1970-01-01
    • 2014-08-11
    • 1970-01-01
    • 2011-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多