settimeout - Remove childElements one-by-one in pure JavaScript -
i have:
<div id="alerts"> <div class="alert">alert 1</div> <div class="alert">alert 2</div> </div>
and want remove these alerts one-by-one after 4000 ms interval of 500 ms in pure javascript.
i have this:
window.onload = function(){ alerts = document.getelementbyid( 'alerts' ); if( alerts ){ alert = alerts.getelementsbyclassname( 'alert' ); settimeout( function(){ for( var i=0; < alert.length; i++ ){ ( function( ){ settimeout( function(){ alerts.removechild( alert[i] ); }, 500); } )(i); } }, 4000); } }
i think not right way of using settimeout
.
the getelementsbyclassname returns live collection means when selected element removed or changed in dom referred collection changes.
so in example when start alert
has 2 elemnets, when first element removed alert
have 1 element referring alert[1]
undefined.
so solution remove first element array.
window.onload = function() { var alerts = document.getelementbyid('alerts'); if (alerts) { alert = alerts.getelementsbyclassname('alert'); settimeout(function() { (var = 0; < alert.length; i++) { (function(i) { settimeout(function() { alerts.removechild(alert[0]); }, * 500); //need increasing timeouts })(i); } }, 4000); } }
<div id="alerts"> <div class="alert">alert 1</div> <div class="alert">alert 2</div> </div>
but can use setinterval() solve in better way like
window.onload = function() { var alerts = document.getelementbyid('alerts'); if (alerts) { var alert = alerts.getelementsbyclassname('alert'); settimeout(function() { var interval = setinterval(function() { alerts.removechild(alert[0]); if (!alert.length) { clearinterval(interval) } }, 1000); }, 3000); } }
<div id="alerts"> <div class="alert">alert 1</div> <div class="alert">alert 2</div> </div>
Comments
Post a Comment