Javascript-форум (https://javascript.ru/forum/)
-   Общие вопросы Javascript (https://javascript.ru/forum/misc/)
-   -   Как кнопкой остановить SetInterval? (https://javascript.ru/forum/misc/71024-kak-knopkojj-ostanovit-setinterval.html)

gooodwin67 19.10.2017 20:41

Как кнопкой остановить SetInterval?
 
Привет товарищи.
Задача такая. Одной кнопкой запускаем SetInterval, другой кнопкой нужно его остановить и запустить другой SetInterval.
Вот пример:

https://jsfiddle.net/gooodwin67/m42qx7ej/

Заранее спасибо!

Rasy 19.10.2017 22:01

gooodwin67,
function abc($el, o, o1) {
  $el.animate(o,1000)
      .animate(o1,1000, function() {
          abc($el, o, o1);
     });
}

$elem = $('.test1');
$('.but1').click(function(){
	abc($elem, {'left':'100px'}, {'left':'0'});
});
$('.but2').click(function(){
	abc($elem, {'top':'100px'}, {'top':'0'});
});

рони 20.10.2017 06:59

gooodwin67,
<!DOCTYPE html>

<html>
<head>
  <title>Untitled</title>
  <meta charset="utf-8">
  <style type="text/css">
  .test1 {
  position:relative;
}
button {
  margin-top: 120px;
}
  </style>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>

  <script>
$(function() {
function abc() {
  $('.test1').animate({'left':'100px'},1000).animate({'left':'0'},1000,abc);
}

function abc2() {
  $('.test1').animate({'top':'100px'},1000).animate({'top':'0'},1000,abc2);
}

//---------------------------------------------------
$('.but1').click(function(){
$('.test1').stop(true);
 abc();
})

$('.but2').click(function(){
 $('.test1').stop(true);
 abc2();
})

});
  </script>
</head>

<body>
<div class = 'test1'>a</div>
<button class = 'but1'>кнопка1</button>
<button class = 'but2'>кнопка2</button>
</body>
</html>

gooodwin67 20.10.2017 08:13

рони, В очередной раз браво!


Часовой пояс GMT +3, время: 23:17.