How to make setTimeout function a continuous loop?

How can I make the setTimeout function a continuous loop?

for instance

setTimeout(function(){ $(".slide2").hide(); $(".slide").show(); setTimeout(function(){ $(".slide").hide(); $(".slide2").show(); }, 1000); }, 1000); 
+4
source share
3 answers

setInterval is actually evil, if the code inside setInterval takes longer than the time you set, it will create another process before the function finishes ruining everything. So choosing setTimeout is actually better.

To make function loops in setTimeout , use the following syntax:

 function function1() { console.log({} + [] + " = {} + []"); // run this it is actually funny } function runner() { function1(); setTimeout(function() { runner(); }, time); } runner(); 
+5
source

You can reduce your nesting and probably use setTimeout , and the switch will take care of the rest (show your first default element before executing.).

 function slideEm() { $(".slide2").toggle(); $(".slide").toggle(); // Make this visible first window.setTimeout(slideEm, 1000); } slideEm(); 

Or use setInterval

 function slideEm() { $(".slide2").toggle(); $(".slide").toggle(); // Make this visible first } $(function(){ $('.slide').show(); //Using css hide both of them and show this first window.setInterval(slideEm, 1000); // start the callback loop with a sec interval }); 

Demo

+3
source

Use setInterval and toggle() instead.

 setInterval(function () { $(".slide2").toggle(); $(".slide").toggle(); }, 1000); 

JsFiddle example

+2
source

Source: https://habr.com/ru/post/1486420/


All Articles