Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setTimeout runs only once?

function slide() {     if($('.current').is(':last-child')){         $('.current').removeClass('.current');         $('#imgholder').first().addClass('.current');         $('#imgholder').animate({left: '3920px'});     }     else{         $nxt=$(".current");         $(".current").removeClass("current");         $nxt.next().addClass("current");         $('#imgholder').animate({left: '-=980'},{duration: 'slow', easing: 'easeOutBounce' });         } } var loop_handle= setTimeout("slide()",'3000'); 

I have put this code in header section and the setTimeout runs only once.

like image 951
pahnin Avatar asked Oct 23 '11 16:10

pahnin


People also ask

Does setTimeout run once?

That's because setTimeout() is supposed to run only once. In order to fire an event on set intervals user setInterval() .

Does setTimeout run multiple times?

There are two methods for it: setTimeout allows us to run a function once after the interval of time. setInterval allows us to run a function repeatedly, starting after the interval of time, then repeating continuously at that interval.

How many times setTimeout executed?

As specified in the HTML standard, browsers will enforce a minimum timeout of 4 milliseconds once a nested call to setTimeout has been scheduled 5 times.

Does setTimeout stop execution?

No, setTimeout does not pause execution of other code.


2 Answers

setTimeout should only run once. You're looking for setInterval.

var loop_handle = setInterval(slide, 3000); 

Also, the second argument should be a number, not a string. When the function call doesn't require any arguments, it's better to reference to the function instead of using a string. A string would be converted to a function. This function will be executed within the scope of the window.

  setInterval("slide()", 3000); //becomes   setInterval(Function("slide();"), 3000); 
like image 112
Rob W Avatar answered Sep 20 '22 04:09

Rob W


Yes, setTimeout only runs once. You want setInterval. This function also returns an ID you can use to cancel the interval. For example:

const slideInterval = setInterval(slide, 3000);  // later... clearInterval(slideInterval); 
like image 26
uɥƃnɐʌuop Avatar answered Sep 20 '22 04:09

uɥƃnɐʌuop