DEVHIDE
        • Home (current)
        • About
        • Contact
        • Cookie
        • Home (current)
        • About
        • Contact
        • Cookie
        • Disclaimer
        • Privacy
        • TOS
        Login Or Sign up

        How to join setInterval and .on("click") function together?

        1.6k Views Asked by AudioBubble At 16 June 2015 at 20:13 2025-12-06T15:35:53.095000

        I have an extremely primitive slider using fadeIn, fadeOut and some control bullets.

        https://jsfiddle.net/c2dsnr8v/1/

        <div class="view">
          <ul class="list">
            <li class="frst">
              <img src="http://www.guessthelogo.com/wp-content/uploads/2012/11/random-dice.gif" />
            </li>
            <li class="scnd">
              <img src="https://avatars.yandex.net/get-music-content/a19fc9b4.a.1767585-1/200x200" />
            </li>
            <li class="thrd">
              <img src="http://randomacts.channel4.com/images/fb_logo.gif" />
            </li>
            <li class="frth">
              <img src="http://cs620120.vk.me/v620120530/93f0/k7U9HGQOBkw.jpg" />
            </li>
          </ul>
          <div class="ctrl">
            <div class="bullet one"></div>
            <div class="bullet two"></div>
            <div class="bullet three"></div>
            <div class="bullet four"></div>
          </div>
        </div>
        
        $(".list li:gt(0)").hide();
        
        var int = setInterval(function(){
        $('.list > :first-child')
        .fadeOut()
        .next()
        .fadeIn()
        .end()
        .appendTo('.list');} ,3000);
        
        $(".bullet").on("click", function(){
          clearInterval(int);
          $(".list li").fadeOut();
        
          var $this = $(this);
        
          if($this.hasClass("one")){
            $(".list li.frst").fadeIn();
          }else if($this.hasClass("two")){
            $(".list li.scnd").fadeIn();
          }else if($this.hasClass("three")){
            $(".list li.thrd").fadeIn();
          }else if($this.hasClass("four")){
            $(".list li.frth").fadeIn();
          }
        })
        

        I figured out how I can make pictures appear on clicking bullets (green squares), and the setInterval function here is clear enough. But when I tried to join these mechanisms together, I found out that I can only clear setInterval with a click. So once I use bullets, automatic rotating doesn't work anymore.

        Is there any way to join the two together, using this code? For example, I click on a bullet, the picture stands still for 5 seconds, and then it keeps rotating further with the same speed?

        I tried to include a new setInterval after each bullet click, but failed.

        javascript jquery html slider setinterval
        Original Q&A
        3

        There are 3 best solutions below

        1
        dgavian dgavian On 17 June 2015 at 18:10 BEST ANSWER

        Here is an updated snippet that removes the jumpiness. Basically the issue was in the ".appendTo('.list');", which reordered the list items and made it difficult to continue the rotation once a bullet was clicked. The code significantly changed to get around this, but it should be more efficient since the dom isn't being reordered every time through. Also, I removed a bunch of unnecessary classes and and am now using .index() to coordinate between the bullets and list items, as mentioned previously.

        (function() {
          var start = function() {
              var active = $('.active'),
                next = active
                .removeClass('active')
                .fadeOut()
                .next();
              if (!next.length) {
                next = $('ul li:first-child');
              }
              next
                .addClass('active')
                .fadeIn()
                .end();
            },
            go = function() {
              return setInterval(start, 2000);
            },
            int = go();
          $(".bullet").on("click", function() {
            var currentIndex = $('div.bullet').index(this),
              currentLi = $('ul li').eq(currentIndex);
            clearInterval(int);
            $('.active').removeClass('active').fadeOut();
            currentLi.addClass('active').fadeIn();
            int = go();
          })
        }());
        .view {
          margin: 100px auto 0;
          width: 200px;
          position: relative;
        }
        ul {
          margin: 0;
          padding: 0;
          list-style: none;
          position: relative;
        }
        ul li {
          position: absolute;
          top: 0;
          left: 0;
        }
        .ctrl {
          bottom: -215px;
          display: flex;
          justify-content: space-between;
          position: absolute;
          width: 100%;
        }
        .bullet {
          background-color: green;
          height: 10px;
          width: 10px;
          cursor: pointer;
        }
        <div class="view">
          <ul>
            <li class="active">
              <img src="http://www.guessthelogo.com/wp-content/uploads/2012/11/random-dice.gif" />
            </li>
            <li style="display:none;">
              <img src="https://avatars.yandex.net/get-music-content/a19fc9b4.a.1767585-1/200x200" />
            </li>
            <li style="display:none;">
              <img src="http://randomacts.channel4.com/images/fb_logo.gif" />
            </li>
            <li style="display:none;">
              <img src="http://cs620120.vk.me/v620120530/93f0/k7U9HGQOBkw.jpg" />
            </li>
          </ul>
          <div class="ctrl">
            <div class="bullet"></div>
            <div class="bullet"></div>
            <div class="bullet"></div>
            <div class="bullet"></div>
          </div>
          <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>

        1
        McSick McSick On 16 June 2015 at 20:31

        I think what you are looking for is setTimeout. setTimeout will execute a function once after a set amount of milliseconds. So in this example you can do:

        //clear timeoutid incase you click a lot
        clearTimeout(timeoutid);
        timeoutid = setTimeout(function(){ 
          int = setInterval(function(){
            //List stuff
          },2000);
        },3000);
        

        So in this case the next fade wont happen for 5 seconds after the click, but the rotation will continue on a 2 second interval.

        Example JSFiddle:
        https://jsfiddle.net/u6sdb40j/1/

        1
        dgavian dgavian On 16 June 2015 at 21:15

        You can use an immediate function to encapsulate your vars and functions and avoid calling setInterval twice:

        (function() {
          $(".list li:gt(0)").hide();
          var start = function() {
              $('.list > :first-child')
                .fadeOut()
                .next()
                .fadeIn()
                .end()
                .appendTo('.list');
            },
            go = function(elem) {
              return setInterval(start, 2000);
            },
            int = go();
          $(".bullet").on("click", function() {
            clearInterval(int);
            $(".list li").fadeOut();
            var $this = $(this);
            if ($this.hasClass("one")) {
              $(".list li.frst").show();
            } else if ($this.hasClass("two")) {
              $(".list li.scnd").show();
            } else if ($this.hasClass("three")) {
              $(".list li.thrd").show();
            } else if ($this.hasClass("four")) {
              $(".list li.frth").show();
            };
            setTimeout(function() {
              int = go();
            }, 2000);
          })
        }());
        

        (function() {
          $(".list li:gt(0)").hide();
          var start = function() {
              $('.list > :first-child')
                .fadeOut()
                .next()
                .fadeIn()
                .end()
                .appendTo('.list');
            },
            go = function(elem) {
              return setInterval(start, 2000);
            },
            int = go();
          $(".bullet").on("click", function() {
            clearInterval(int);
            $(".list li").fadeOut();
            var $this = $(this);
            if ($this.hasClass("one")) {
              $(".list li.frst").show();
            } else if ($this.hasClass("two")) {
              $(".list li.scnd").show();
            } else if ($this.hasClass("three")) {
              $(".list li.thrd").show();
            } else if ($this.hasClass("four")) {
              $(".list li.frth").show();
            };
            setTimeout(function() {
              int = go();
            }, 2000);
          })
        }());
        .view {
          margin: 100px auto 0;
          width: 200px;
          position: relative;
        }
        .list {
          margin: 0;
          padding: 0;
          list-style: none;
          position: relative;
        }
        .list li {
          position: absolute;
          top: 0;
          left: 0;
        }
        .ctrl {
          bottom: -215px;
          display: flex;
          justify-content: space-between;
          position: absolute;
          width: 100%;
        }
        .bullet {
          background-color: green;
          height: 10px;
          width: 10px;
          cursor: pointer;
        }
        <div class="view">
          <ul class="list">
            <li class="frst">
              <img src="http://www.guessthelogo.com/wp-content/uploads/2012/11/random-dice.gif" />
            </li>
            <li class="scnd">
              <img src="https://avatars.yandex.net/get-music-content/a19fc9b4.a.1767585-1/200x200" />
            </li>
            <li class="thrd">
              <img src="http://randomacts.channel4.com/images/fb_logo.gif" />
            </li>
            <li class="frth">
              <img src="http://cs620120.vk.me/v620120530/93f0/k7U9HGQOBkw.jpg" />
            </li>
          </ul>
          <div class="ctrl">
            <div class="bullet one"></div>
            <div class="bullet two"></div>
            <div class="bullet three"></div>
            <div class="bullet four"></div>
          </div>
          <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>

        There is some initial "jumpiness" after clicking a bullet before it settles in that you might have to tweak. Also, you could probably clean up some of your code by using jQuery's .index() method, if desired.

        Related Questions in JAVASCRIPT

        • Angular Show All When No Filter Is Supplied
        • Why does a function show up as not defined
        • I count the time the user takes to solve my quiz using Javascript but I want the same time displayed on another page
        • Set "More" "Less" font size
        • Using pagination on a table in AngularJS
        • How to sort these using Javascript or Jquery Most effectively
        • how to fill out the table with next values in array with one button
        • State with different subviews
        • Ajax jQuery firing multiple time display event for the same result
        • Getting and passing MVC Model data to AngularJS controller
        • Disable variable in eval
        • javascript nested loops waiting for user input
        • .hover() seems to overwrite .click()
        • How to sort a multi-dimensional array by the second array in descending order?
        • How do I find the fonts that are not loading in a CORS situation ( MoovWeb )?

        Related Questions in JQUERY

        • How to sort these using Javascript or Jquery Most effectively
        • Ajax jQuery firing multiple time display event for the same result
        • .hover() seems to overwrite .click()
        • Check for numeric value with optional commas javascript
        • Extending Highmaps Side Effect
        • Array appending after each onclick and loop in javascript
        • how can i append part of a table based on how many tr it has?
        • Play multiple audio files in a slider
        • Remove added set of rows
        • Access property of an object of type [Model] in JQuery
        • AJAX PHP - Reload div after submit
        • proengsoft/laravel-jsvalidation ReferenceError: jQuery is not defined
        • when a checkbox is checked how to display a different hidden element using javascript
        • Get jquery error Uncaught RangeError: Maximum call stack size exceeded
        • Removing only the closest thead on table filtering

        Related Questions in HTML

        • Delay in loading Html Page(WebView) from assets folder in real android device
        • Why does a function show up as not defined
        • CSS Class is not applying to element (border width,color,and style attributes)
        • How to sort these using Javascript or Jquery Most effectively
        • how to fill out the table with next values in array with one button
        • Automatically closing tags in form input?
        • Positioning child at bottom of parent with scroll
        • Remove added set of rows
        • Website zoomed out on Android default browser
        • Twitter Bootstrap horizontal form elements on a line
        • http://sigmajs.org/ les mis tutorial - why are my canvases 0 height?
        • My navbar is not expanding after collapse
        • when a checkbox is checked how to display a different hidden element using javascript
        • Gaps Vertically Using Dividers
        • Svg containers not positioning properly

        Related Questions in SLIDER

        • Navigation for slider by checkbox
        • I need a event for the slider it should fire only if user ends touching the control
        • AngularJS Dynamic Slider Control
        • Jssor slider different height on landscape
        • Image slider performance
        • I want to display my text after my thumbnail slider div
        • Connect range slider Jquery
        • JQuery simple-slider
        • jssor sliders swipe in the same time
        • CSS Slider's Tab's Active Class (Bootstrap) doesn't work on second slide
        • Use XAML StringFormat to get one decimal place
        • Q: Jssor account for body padding in Scalewidth
        • Materialize making slider images responsive
        • Custom Slider Not Sliding involves XSL
        • how to use wx.Slider with SELRANGE?

        Related Questions in SETINTERVAL

        • Change setInterval value dynamically
        • setTimeout with condition inside before running again
        • Is it true that if possible I should never use setInterval & setTimeout?
        • How to evenly time fading transitions?
        • how can i use $interval in for loop
        • Javascript how to start script on exact time
        • Javascript loading slow down when tab changes
        • Javascript setInterval doesn't work correctly when tab is not active
        • how to avoid mouse event conflict with timer
        • ASP.NET Updating a list using jQuery AJAX
        • clearTimeout not working - setinterval problems
        • How to join setInterval and .on("click") function together?
        • Scroll tabs with animation - Stop setInterval immediately on mouseup
        • ExtJs taskrunner using Slider
        • Can't call setInterval twice

        Trending Questions

        • UIImageView Frame Doesn't Reflect Constraints
        • Is it possible to use adb commands to click on a view by finding its ID?
        • How to create a new web character symbol recognizable by html/javascript?
        • Why isn't my CSS3 animation smooth in Google Chrome (but very smooth on other browsers)?
        • Heap Gives Page Fault
        • Connect ffmpeg to Visual Studio 2008
        • Both Object- and ValueAnimator jumps when Duration is set above API LvL 24
        • How to avoid default initialization of objects in std::vector?
        • second argument of the command line arguments in a format other than char** argv or char* argv[]
        • How to improve efficiency of algorithm which generates next lexicographic permutation?
        • Navigating to the another actvity app getting crash in android
        • How to read the particular message format in android and store in sqlite database?
        • Resetting inventory status after order is cancelled
        • Efficiently compute powers of X in SSE/AVX
        • Insert into an external database using ajax and php : POST 500 (Internal Server Error)

        Popular # Hahtags

        javascript python java c# php android html jquery c++ css ios sql mysql r reactjs

        Popular Questions

        • How do I undo the most recent local commits in Git?
        • How can I remove a specific item from an array in JavaScript?
        • How do I delete a Git branch locally and remotely?
        • Find all files containing a specific text (string) on Linux?
        • How do I revert a Git repository to a previous commit?
        • How do I create an HTML button that acts like a link?
        • How do I check out a remote Git branch?
        • How do I force "git pull" to overwrite local files?
        • How do I list all files of a directory?
        • How to check whether a string contains a substring in JavaScript?
        • How do I redirect to another webpage?
        • How can I iterate over rows in a Pandas DataFrame?
        • How do I convert a String to an int in Java?
        • Does Python have a string 'contains' substring method?
        • How do I check if a string contains a specific word?

        Copyright © 2021 Jogjafile Inc.

        • Disclaimer
        • Privacy
        • TOS
        • Homegardensmart
        • Math
        • Aftereffectstemplates