javascript - setInterval 执行速度太快

标签 javascript jquery

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

我在不同的文件中有多个 setInterval,它们具有各自的功能:

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

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

    $('.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);
        }
    }
    
<小时/>

UPDATE

由于点击 .item 时会显示一个模态,以避免多次 setInterval。

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

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

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

最佳答案

您没有在每次单击 .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>

关于javascript - setInterval 执行速度太快,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39783958/

相关文章:

javascript - 使用 Javascript 创建询问输入用户名和密码的提示的最佳方法是什么

javascript - 如何修复我的 jQuery 按钮 slider ?

javascript - Ajax POST 不起作用/扭曲

javascript - 在 if 中重新定义变量并像 php 一样在外部使用它

jquery - FlexSlider有销毁方法吗

jQuery 可排序+可删除。掉落后,我的 LI 被另一个 LI 包裹着

javascript - 在 v5 中扩展 d3.selection——这是正确的做法吗?

javascript - Ember.js:属性更改时不调用 Controller 属性

jquery - 将 jquery 自动完成的源设置为 mysql 表

javascript - 我可以显示/隐藏部分 div 吗?