javascript - Expire or Time Out never ending loop after X seconds -


how can stop process after, say, 5 seconds?

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> <script type="text/javascript">     function changebanner(){          // change banner code     }     window.onload = function () { setinterval(changebanner, 100) }; </script> 

so changing banner every 100 milliseconds. i'd stop after 5 seconds.

i thought settimeout might trick;

window.onload = function () { settimeout(setinterval(changebanner, 100), 5000) }; 

but makes no difference.

i'd stop after 5 seconds.

store return value given setinterval , use clearinterval

var timer = setinterval(changebanner, 100); settimeout(function() {     clearinterval(timer) }, 5000); 

there several libraries implement function wrappers achieve same. example, in underscore.js use _.before:

var changebannerlimited = _.before(50, changebanner); var timer = setinterval(changebannerlimited, 100); 

note contrary using clearinterval continue call changebannerlimited function forever, after being called 50 times (10 * 5 seconds) no longer pass call on changebanner.

on side note chose underscore.js because know , because provides nicely formated annotated source code can understand what's going on behind scenes.


Comments

Popular posts from this blog

java - Jasper subreport showing only one entry from the JSON data source when embedded in the Title band -

serialization - Convert Any type in scala to Array[Byte] and back -

SonarQube Plugin for Jenkins does not find SonarQube Scanner executable -