简体   繁体   中英

Using setInterval with variable not working on iOS

I'm using setInterval with a mousedown event to continuously animate some divs like a slider.

I'm also setting a variable to setInterval so that I can stop the animation on mouseup .

This works fine except on iOS where it will only animate the divs if I remove the variable (int00) and operator in front of setInterval in the mousedown function:

var int00;

$('#scroll_diseases_left').mousedown(function(){
    int00 = setInterval(function() { scroll_diseases_left(); }, 250);
});

$('#scroll_diseases_left').mouseup(function(){
    clearInterval(int00);
});

function scroll_diseases_left() {
    $('#scroll_diseases_right').fadeIn();
    $('#disease_wrapper').animate({marginLeft: '-=50px'}, {duration: 500, queue: false, easing: 'linear'});
    $('#arthritis_content').animate({marginLeft: '-=50px'}, {duration: 500, queue: false, easing: 'linear'});
    $('#bleeding_content').animate({marginLeft: '-=50px'}, {duration: 500, queue: false, easing: 'linear'});
    $('#blood_vessel_content').animate({marginLeft: '-=50px'}, {duration: 500, queue: false, easing: 'linear'});
    $('#brain_content').animate({marginLeft: '-=50px'}, {duration: 500, queue: false, easing: 'linear'});
    $('#cancer_content').animate({marginLeft: '-=50px'}, {duration: 500, queue: false, easing: 'linear'});
}

Any ideas?

UPDATE

Declaring int00 as a local variable in the mousedown function works on iOS, but then I can't stop the animations...

$('#scroll_diseases_left').mousedown(function(){
    var int00 = setInterval(function() { scroll_diseases_left(); }, 250);
});

$('#scroll_diseases_left').mouseup(function(){
    clearInterval(int00);
});

The problem was that the touch event on iOS wasn't being picked up. This works:

  $('#scroll_diseases_left').bind('touchstart mousedown', function(){
   int00 = int00 || setInterval(function() { scroll_diseases_left(); }, 250);
  });

  $('#scroll_diseases_left').bind('touchend mouseup', function(){
      clearInterval(int00);
      int00 = undefined;
  });

The problem is you need some logic to test if int00 is set before you reset it.

  var int00;

  $('#scroll_diseases_left').mousedown(function(){

   // if int00 is set, keep it, if it is not start a new interval.

   int00 = int00 || setInterval(function() { scroll_diseases_left(); }, 250);
  });

  $('#scroll_diseases_left').mouseup(function(){
      clearInterval(int00);
      int00 = undefined;
  });

Just a guess here, but perhaps iOS doesn't like automatic globals.

Try placing var int00; before other code to declare the variable. It's good practice anyways.

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