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-19T23:04:15.174054

        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

        • Using Puppeteer to scrape a public API only when the data changes
        • inline SVG text (js)
        • An array of images and a for loop display the buttons. How to assign each button to open its own block by name?
        • Storing the preferred font-size in localStorage
        • Simple movie API request not showing up in the console log
        • Authenticate Flask rest API
        • Deploying sveltekit app with gunjs on vercel throws cannot find module './lib/text-encoding'
        • How to request administrator rights?
        • mp4 embedded videos within github pages website not loading
        • Scrimba tutorial was working, suddenly stopped even trying the default
        • In Datatables, start value resets to 0, when column sorting
        • How do I link two models in mongoose?
        • parameter values only being sent to certain columns in google sheet?
        • Run main several times of wasm in browser
        • Variable inside a Variable, not updating

        Related Questions in JQUERY

        • In Datatables, start value resets to 0, when column sorting
        • Bootstrap modal not showing at the desired position on a web page when the screen size is smaller
        • window.location.href redirects but is causing problems on the webpage
        • Using JQuery Date Slider
        • Storing selected language in localStorage
        • How to stop other divs from still showing when i click a different button?
        • Check multiple values with jQuery
        • Bootstrap component does not want to render in Datatables function
        • put white spaces when entering an amount moneytype symfony
        • Trouble accessing custom header in AJAX response using jQuery in Fiware Keyrock
        • I just cant make it work, HTML, JS and Firebase error
        • Didn't declared variable still not getting any error in JavaScript
        • Move element horizontally while scrolling vertically in pure JavaScript
        • allow multi carousel in same page
        • Embedded TikTok posts / thumbnail styling issue

        Related Questions in HTML

        • How to store a date/time in sqlite (or something similar to a date)
        • How to use custom font during html to pdf conversion?
        • Storing the preferred font-size in localStorage
        • mp4 embedded videos within github pages website not loading
        • Scrimba tutorial was working, suddenly stopped even trying the default
        • Is there any way to glow this bulb image like a real light bulb
        • With non-graphical maps in Leaflet, zoomDelta doesn't work
        • What can I do to improve my coding on both html and css
        • Uncaught TypeError: google.maps.LatLng is not a constructor at init (script.js:7:13)
        • Bootstrap modal not showing at the desired position on a web page when the screen size is smaller
        • Displaying a Movie List on a Website Using Jinja2 and Bootstrap
        • How to redirect to thank you page after submitting a Google form embedded into a Google Site?
        • Storing selected language in localStorage
        • Fences (parenthesis, braces) in HTML and MathML
        • Understanding Scroll Anchoring Behavoir

        Related Questions in SLIDER

        • Using JQuery Date Slider
        • Swiper.js moves slides outside of viewport/page
        • Swiper Js Slider Reveal Next Slider Partially
        • MAUI slider with a tooltip implementation
        • Slider react-slick
        • Slider revolution is not showing up on my wordpress pages just white space
        • How to make a single slider with three pointer
        • Positioning for sliders and canvas
        • How to make a DAX formula respond to a Timeline slider?
        • Swiperjs breakpoints doesn't apply when reach the breakpoints
        • How can i make a infinite horizontal scroll that recibes input from mouse wheel with Javascript & React
        • CSS image slider carousel with cross fade - how to get timing right?
        • How to make custom triangle slider fill in tailwind
        • how do i create slider on Wix website builder?
        • Webapp exiting fullscreen when dragging mui slider in iPads

        Related Questions in SETINTERVAL

        • Main thread frozen handling interval, sending accumulated data with enormous delay
        • IF Else statement not properly worked in setInterval() function while creating count-down timer
        • How to detect a pressed button using setInterval and without any event in javascript?
        • react the function of key and useEffect
        • How to build a responsive timer for a multiplayer game
        • Angular 17 does not update view using setInterval with NG0500 error in console
        • clearInterval() doesn't stop setInterval() method
        • NodeJS: WorkerThread or setInterval?
        • Why setTimeout is not working in nodejs server?
        • setnterval is acting unpredictably in React Project causing multiple changes to State Array
        • Enabling setInterval or react-idle-timer to Run in Computer Sleep Mode
        • Interval function causes infinite UI load unless I type in "/index.html" in the URL
        • The SetInterval function does'nt work in Angular 17
        • How can I make the instances of my SuperCounter class stop counting independently?
        • In Redux Toolkit, how to call a reducer function from the inside of the other

        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