I have two buttons, the first should start in 3 seconds, the second in 1.5. For this purpose, I wrote a function

var start = setInterval(function(){ autoLoopSlider() }, 3000); function autoLoopSlider(button, time) { $(button).click(); setTimeout(autoLoopSlider, time); } autoLoopSlider(".button_1", 3000); autoLoopSlider(".button_2", 1500); function myStopFunction() { clearInterval(start); } 

But for some reason it does not work, tell me what I was wrong and how to fix the situation

  • Well, because in the first line, the error will be - you pass the function without parameters and when you call the function, Jquery (button is undefined) and setTimeout (time is undefined) will swear. The second point is the link . The setTimeout function is called asynchronously after a specified period of time. - alexoander

1 answer 1

If I understand you correctly, then you need something like this:

 $(document).ready(function() { $(".button1").click(function() { console.log("halo1"); }); $(".button2").click(function() { console.log("halo122"); }); function autoLoopSlider(button, time) { setTimeout(function() { $(button).click(); }, time); }; var intervall = setInterval(function() { autoLoopSlider(".button1", 3000); autoLoopSlider(".button2", 1500); }, 1000); // где то тут нужно очищать интервал, когда он тебе уже не нужен }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script> <div class="content"> <input type="button" class="button1" value="but1"> <input type="button" class="button2" value="but2"> </div> 

  • and how to make it so that the function is restarted after working off, does it need to write recursion? - ChromeChrome
  • one
    just add setInterval(function(){ autoLoopSlider(".button1", 3000); autoLoopSlider(".button2", 1500);},100); instead of the code after the autoLoopSlider function. Then every 100 ms a code will be called that will call up your buttons in 1500 and 3000 ms, respectively. However, I would be afraid of callbackHell errors. Therefore, somewhere here you need to clear the interval after execution. - alexoander