0
<html>
<head>
<script src="jquery.js"></script>
<script>
$(document).ready(function(){
    setInterval(function(){
    var i = 1;
        while(i<3){

             var left = $("#"+i).offset().left;
            $("#"+i).css({'left':left}).animate({'left':'-10000px'},8000);
            if(i == 1){
                i++;
            }
            if(i == 2){
                i--;
            }
        }


    },2500);

});
</script>
</head>

<body>
<div id=myDivWrapper style="overflow:hidden">
<div id=1 style="right:0;width:100%;height:100%;background:url('1.jpg');position:absolute;"></div>
<div id=2 style="right:0;width:100%;height:100%;background:url('2.jpg');">
</div>
<body>
</html>

I'm trying to create a JQuery image slider using while loop. here i is the integer i'm incrementing. I don't want the i to be 3 so the loop will stop. Therefor i used a decision statement for finding if i is 1 increment it and if i is 2 decrement it. But this causes lag on browser and it doesn't work. I know this script is crazy. But can you figure out where I made mistake?

3
  • 2
    Every 2.5 seconds, you call a function that has a never ending loop, why? Commented Aug 10, 2013 at 7:08
  • i think it has something to do with your animation time. Reduce it to <= 2500 and see what happens Commented Aug 10, 2013 at 7:26
  • Why are you using while(i<3) if you "don't want the i to be 3"? If it never gets to 3 the loop will never end... Could you describe what your desired effect is (as seen by the user)? Commented Aug 10, 2013 at 7:48

2 Answers 2

2

Your problem is here..

if(i == 1){
   i++;
}
if(i == 2){
    i--;
}

See when i is 1, first statement becomes true and then second if will going to be executed so at that time i is 2 so again it decrements value of i. So this is the problem that causes lag on browser. Use else or else if to solve this.

Here it is.

if(i == 1) {
    i++;
}
else {
    i--;
}

OR

if(i == 1) {
   i++;
}
else if(i==2) {
  i--;
}

Both are same and will work for you.

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

Comments

1

Use like below:

    if(i == 1){
        i++;
    }else if(i == 2){
        i--;
    }

You should use else

Comments

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.