2017-01-20 7 views
0

мне нужно очистить интервал функции в этом примереКак очистить интервал внутри функции, называющей себя Javascript

$.fn.bounce = function(options) { 

    var settings = $.extend({ 
     speed: 10 
    }, options); 

    return $(this).each(function() { 

     var $this = $(this), 
      $parent = $this.parent(), 
      height = $parent.height(), 
      width = $parent.width(), 
      top = Math.floor(Math.random() * (height/2)) + height/4, 
      left = Math.floor(Math.random() * (width/2)) + width/4, 
      vectorX = settings.speed * (Math.random() > 0.5 ? 1 : -1), 
      vectorY = settings.speed * (Math.random() > 0.5 ? 1 : -1); 

     // place initialy in a random location 
     $this.css({ 
      'top': top, 
      'left': left 
     }).data('vector', { 
      'x': vectorX, 
      'y': vectorY 
     }); 

     var move = function($e) { 

      var offset = $e.offset(), 
       width = $e.width(), 
       height = $e.height(), 
       vector = $e.data('vector'), 
       $parent = $e.parent(); 

      if (offset.left <= 0 && vector.x < 0) { 
       vector.x = -1 * vector.x; 
      } 
      if ((offset.left + width) >= $parent.width()) { 
       vector.x = -1 * vector.x; 
      } 
      if (offset.top <= 0 && vector.y < 0) { 
       vector.y = -1 * vector.y; 
      } 
      if ((offset.top + height) >= $parent.height()) { 
       vector.y = -1 * vector.y; 
      } 

      $e.css({ 
       'top': offset.top + vector.y + 'px', 
       'left': offset.left + vector.x + 'px' 
      }).data('vector', { 
       'x': vector.x, 
       'y': vector.y 
      }); 

      setTimeout(function() { 
       move($e); 
      }, 50); 

     }; 

     move($this); 
    }); 

}; 

$(function() { 
    $('#wrapper li').bounce({ 
     'speed': 7 
    }); 
}); 

Поэтому, когда мне нужно я начинаю оживлённый круг, и когда я не хочу, я могу остановиться. Таким образом, в приведенном выше коде вы можете видеть, что move($this); получает вызов через интервал, что мне нужно, чтобы остановить или очистить интервал, чтобы круг переставал анимировать. и когда снова мне нужно, я могу просто нажать кнопку, и снова запустит анимацию.

+0

Вы должны добавить переменную, которую вы можете проверить, прежде чем вызывать setTimeout. – scrappedcola

+0

Возможный дубликат [Javascript - Пауза setInterval()] (http://stackoverflow.com/questions/21277900/javascript-pausing-setinterval) –

+0

Знаете ли вы разницу между setTimeout и setInterval? – zsawaf

ответ

1

Я разделил свой код в bounce функции на три секции:

  1. One для инициализации, когда элемент занял свои стартовые позиции.
  2. Еще для логики анимации (с начала и остановки добавлены)
  3. Последний один для движения (ту же функцию move но insetead опредиления его внутри each (не очень хорошо, потому что он будет получать redifined для каждого элемента), Я определил его за пределами each).

Код содержит тонны комментариев. Если что-то еще неясно, напишите комментарий ниже.

$.fn.bounce = function(options) { 
 

 
    var settings = $.extend({ 
 
     speed: 10 
 
    }, options); 
 

 
    // Keep a reference to this to use when we are inside bounded functions (where this is something different) 
 
    var that = this; 
 
    
 
    
 
    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 
 
    ///////////////////////////////////////////////// LOGIC FOR INITIALIZATION /////////////////////////////////////////////// 
 
    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 
 
    // function init to initialize the elements. 
 
    function init(){ 
 
     $(that).each(function() { 
 

 
      var $this = $(this), 
 
       $parent = $this.parent(), 
 
       height = $parent.height(), 
 
       width = $parent.width(), 
 
       top = Math.floor(Math.random() * (height/2)) + height/4, 
 
       left = Math.floor(Math.random() * (width/2)) + width/4, 
 
       vectorX = settings.speed * (Math.random() > 0.5 ? 1 : -1), 
 
       vectorY = settings.speed * (Math.random() > 0.5 ? 1 : -1); 
 

 
      // place initialy in a random location 
 
      $this.css({ 
 
       'top': top, 
 
       'left': left 
 
      }).data('vector', { 
 
       'x': vectorX, 
 
       'y': vectorY 
 
      }); 
 
     }); 
 
    } 
 
    // call it right away (initialize) before starting anything else 
 
    init(); 
 
    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 
 
    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 
 

 
    
 
    
 
    
 
    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 
 
    ///////////////////////////////////////////////// LOGIC FOR ANIMATION /////////////////////////////////////////////// 
 
    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 
 
    // the boolean that will stop the animation 
 
    var keepGoing = false; 
 
    
 
    // If the selector for the start button is specified 
 
    if(settings.start){ 
 
     // attach animate to its click event listener 
 
     $(settings.start).on("click", animate); 
 
    } 
 
    else // no button is provided then start automatically 
 
     animate(); 
 
    // If the selector for the stop button is specified 
 
    if(settings.stop){ 
 
     // attach stop to its click event listener 
 
     $(settings.stop).on("click", stop); 
 
    } 
 
    
 
    // the function that will start the animation 
 
    function animate(){ 
 
     // If we are not already animating 
 
     if(!keepGoing){ 
 
      keepGoing = true; 
 
      // call move on all the elements to start the magic. 
 
      // we use 'that' instead of 'this' here because 'this' is the button that have been clicked (see the event listener above=. 
 
      $(that).each(function() { 
 
       move($(this)); 
 
      }); 
 
     } 
 
    } 
 
    // the function that will stop the animation ... 
 
    function stop(){ 
 
     // ... by simply set keepGoing to false 
 
     keepGoing = false; 
 
    } 
 
    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 
 
    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 
 
    
 
    
 
    
 

 
    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 
 
    /////////////////////////////////////////////////  LOGIC FOR MOVEMENT  /////////////////////////////////////////////// 
 
    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 
 
    // the move function responsible for moving the elements 
 
    function move($e) { 
 

 
     var offset = $e.offset(), 
 
      width = $e.width(), 
 
      height = $e.height(), 
 
      vector = $e.data('vector'), 
 
      $parent = $e.parent(); 
 

 
     if (offset.left <= 0 && vector.x < 0) { 
 
      vector.x = -1 * vector.x; 
 
     } 
 
     if ((offset.left + width) >= $parent.width()) { 
 
      vector.x = -1 * vector.x; 
 
     } 
 
     if (offset.top <= 0 && vector.y < 0) { 
 
      vector.y = -1 * vector.y; 
 
     } 
 
     if ((offset.top + height) >= $parent.height()) { 
 
      vector.y = -1 * vector.y; 
 
     } 
 

 
     $e.css({ 
 
      'top': offset.top + vector.y + 'px', 
 
      'left': offset.left + vector.x + 'px' 
 
     }).data('vector', { 
 
      'x': vector.x, 
 
      'y': vector.y 
 
     }); 
 

 
     // if keep going, ... you know, keep going. 
 
     if(keepGoing){ 
 
      setTimeout(function() { 
 
       move($e); 
 
      }, 50); 
 
     } 
 
    } 
 
    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 
 
    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// 
 
} 
 

 
// the options can have the 'start' and 'stop' selector optionally. 
 
$(function() { 
 
    $('#wrapper li').bounce({ 
 
     'speed': 7, 
 
     'start': '#startAnimation', // selector of the element that when clicked the animation will start. If not provided the animation will start automatically 
 
     'stop' : '#stopAnimation' // selector of the element that when clicked the animation will stop (pause). If not provided the animation will go for ever 
 
    }); 
 
});
body, * { 
 
    padding: 0 !important; margin: 0: } 
 

 
#wrapper { 
 
    width:500px; 
 
    height: 500px; 
 
    border: 
 
     1px solid red; } 
 

 
li { 
 
    position: absolute; 
 
    width: 60px; 
 
    height: 60px;  
 
    -webkit-border-radius: 30px; 
 
    -moz-border-radius: 30px; 
 
    border-radius: 30px; 
 
    background-color:#0FF; 
 
    line-height: 60px; 
 
    text-align:center; 
 
    cursor:pointer; } 
 

 
button{ 
 
    width: 100px; 
 
    height: 30px; 
 
}
<script src='http://code.jquery.com/jquery-3.1.1.min.js'></script> 
 
<ul id="wrapper"> 
 
     <button id="startAnimation">Start</button> 
 
     <button id="stopAnimation">Stop</button> 
 
      <li>1</li> 
 
      <li>2</li> 
 
      <li>3</li> 
 
      <li>4</li> 
 
      <li>5</li> 
 
      <li>6</li> 
 
      <li>7</li> 
 
      <li>8</li> 
 
      <li>7</li> 
 
      <li>8</li> 
 
      <li>9</li> 
 
      <li>10</li> 
 
     </ul>

+0

hi ibrahim спасибо за ваш ответ i попробованный, но не работающий, вы можете посмотреть http://jsfiddle.net/jgJsL/5/, чтобы получить точную идею. –

+0

@AryanSrivastava где или когда вы хотите остановиться? –

+0

как у меня есть 2 кнопки один, чтобы начать действие, а один для остановки активности, поэтому мне нужно реализовать эту кнопку запуска и остановки. –

0

Я думаю, что вы хотите использовать setInterval для этой задачи. Вы можете использовать clearInterval в экземпляре setInterval, который вы создали, чтобы остановить его.

Почему я думаю, что вы должны использовать setInterval вместо setTimeout? Хорошо, потому что setInterval предназначен для запуска функций за определенный промежуток времени (что вы хотите сделать). Где в качестве setTimeout предназначен для задержки вызова функции.

// sample code 
 
var counter = 0; 
 
var example = setInterval(function(){ 
 
    console.log(counter); 
 
    if (counter == 10) { 
 
    console.log("I'm out"); 
 
    clearInterval(example); 
 
    } 
 
    counter++; 
 
}, 300);

0

Вы можете назначить функцию тайм-аута в переменной и использовать метод clearTimeout. Как показано ниже:

var timer = setTimeout(function() { 
      move($e); 
     }, 50); 

clearTimeout(timer); 
Смежные вопросы