It seems like you have your logic backwards. You want to alert the user every time the current time is equal to one of the times in timers
, right? Why not use setInterval()
and skip the for()
loop altogether? If they are already sorted, this works just fine. Also, it seems one if()
would do with a much simpler "compare time by second" method.
I slowed down the process in this demo to make it obvious.
Script:
var timers = [
[new Date( ( new Date() ).getTime() + 3000),'party!'],
[new Date( ( new Date() ).getTime() + 6000), 'sleep']
],
timer = setInterval( checkTime, 300 );
function checkTime() {
if( timers.length ) {
if ( parseInt( timers[0][0].getTime() / 1000 )
== parseInt( new Date().getTime() / 1000 ) ) {
//alert here
document.getElementById( 'result' ).insertAdjacentHTML(
'beforeEnd',
timers[0][0] + ": " + timers[0][1] + '<br />'
);
timers.shift();
};
} else {
clearInterval( timer );
};
};
HTML:
Wait 3 seconds...
<div id="result"></div>