1

I want my trigger to activate every 2 seconds, but each time with my value of i. Like first 3 seconds trigger .slide1, after another 3 seconds .slide2 etc...

Here my code :

    setInterval(function () {
     for ( var i = 0; i < 5; i++ ) {
        $('.slide'+ i).trigger('click');
    }   
}, 3000)

After 3 seconds it immediately trigger my .slide4 and i was wondering why ?

5
  • 3
    Simply because it is what you wrote. :) Commented Jun 3, 2014 at 13:08
  • 1
    Every time the function is called you tell it to trigger the click on all your slides. Commented Jun 3, 2014 at 13:09
  • 1
    After three seconds, your for loop is running in it's entirety, so all of your slides are triggering the click Commented Jun 3, 2014 at 13:09
  • Btw. this is a regular JavaScript for loop, not a jQuery loop (e.g. $.each()) - the thread subject is somewhat confusing. Commented Jun 3, 2014 at 13:12
  • Thanks for the explanation, now my logic is hurt... Hah. Commented Jun 3, 2014 at 13:15

1 Answer 1

2

Try

var slide = 0;
setInterval(function () {
        $('.slide'+ (slide++ % 5)).trigger('click');
}, 3000);

The problem with your code is that each time the interval function is called, you execute the loop and trigger the click event for all the slides.

Sign up to request clarification or add additional context in comments.

5 Comments

Could you explain why you used modulo here ?
@Oliboy50 this way you can keep the counter (slider variable) between 0 and the number you divide. In this case 0-4.
Clever. But are you sure that there will be no issue if user stay on this page a long long long time, cause of the slide integer limit value ?
@Oliboy50 the max integer is 9007199254740992. To reach that by incrementing every 3 seconds, takes approximately (if my calculations are correct) 856 million years ;)
@GabyakaG.Petrioli Thanks for pointing the max integer value ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.