简体   繁体   中英

setInterval executions too fast

There is so many good post regarding this question after their own case, but i cannot find any good answer in my case.

I have a multiple setInterval in different files which serves on their own functions:

  1. The application is a slide show directory, and i have one main setInterval which process the cycle of a custom slideshow in the main app.

     mainInterval = setInterval(changeSlide, 20000); execute after 20 seconds function changeSlide(){ // .... do changes } 
  2. The other one serves as a idle timer when customer click on the information of a slide a modal will appear but when the there is no user interaction the modal will close. This function reside in another javascripts file.

     $('.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

Since there is a modal will show when .item is click and in order to avoid multiple setInterval.

I handle the clearInterval(IdleInterval) when modal hides event triggered.

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

Now the biggest problem is the modal closes before actual 10 seconds is met, when i print the console.log(idleTime); bang! i saw the timer executes faster than normal.

You have not reset the interval every time the .item is clicked which may have caused an issue with multiple intervals running

 // 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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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