0

I have a set-interval function inside a for loop and when inside the set-interval function if it meets a criteria give an alert and clear the interval. Below is my code but its not working can anyone tell what the mistake here.

var timeCheck = 0;
function matchTime() {
    for (var i=0;i<timers.length;i++) {
        timeCheck = setInterval(function () {
            var theDate = new Date(timers[i][0]*1000); 
            var now = new Date(); 
            if ( (now.getFullYear() === theDate.getFullYear()) && (now.getMonth() === theDate.getMonth()) ) {
                if ( (now.getDate() === theDate.getDate()) && (now.getHours() === theDate.getHours()) ) {
                    if ( now.getMinutes() === theDate.getMinutes() && (now.getSeconds() === theDate.getSeconds()) ) { alert("its Time for "+timers[i][1]); stopCheck(); }
                }
            }
        }, 10);
    }
}

function stopCheck() { clearInterval(timeCheck); }

Thanks.

What I am trying to solve is : I need to get an alert every-time when the local time matches the time in the timers array (column 0; timers[count][0]). The array is already sorted
timers.sort(function(a,b) { return a[0] - b[0]; });

user1846348
  • 241
  • 1
  • 10
  • 22
  • What is your code trying to do? – Asad Saeeduddin Feb 26 '13 at 21:45
  • It looks like the classical for loop and settimeout problem. See http://stackoverflow.com/questions/14791158/javascript-settimeout-and-loops – Denys Séguret Feb 26 '13 at 21:46
  • 3
    Any time you find yourself writing "...it's not working..." in a technical question, backspace over it and say *exactly* what you expect it to do, *exactly* what it's doing instead, and why you think that's not correct. – T.J. Crowder Feb 26 '13 at 21:46
  • @dystroy Except that the loop is setting timed loops, not timeouts. That complicates things. – Asad Saeeduddin Feb 26 '13 at 21:48
  • The value of `timeCheck` is being overwritten on each iteration through the for loop. By the time you call the `stopCheck` function, you only have a reference to the last of the intervals you created. – dgvid Feb 26 '13 at 21:48

2 Answers2

0

perhaps:

var timeCheck = {};
function matchTime() {
   for (var i=0;i<timers.length;i++) {
      timeCheck[i] = setInterval(function () {
        var theDate = new Date(timers[i][0]*1000); 
        var now = new Date(); 
        if ( (now.getFullYear() === theDate.getFullYear()) && (now.getMonth() === theDate.getMonth()) ) {
            if ( (now.getDate() === theDate.getDate()) && (now.getHours() === theDate.getHours()) ) {
                if ( now.getMinutes() === theDate.getMinutes() && (now.getSeconds() === theDate.getSeconds()) ) { alert("its Time for "+timers[i][1]); stopCheck(i); }
            }
        }
    }, 10);
    }
}

 function stopCheck(i) { clearInterval(timeCheck[i]); }

or perhaps:

var timeCheck = 0;
function matchTime() {
  var timeCheck = setInterval(function () {
    for (var i=0;i<timers.length;i++) {
        var theDate = new Date(timers[i][0]*1000); 
        var now = new Date(); 
        if ( (now.getFullYear() === theDate.getFullYear()) && (now.getMonth() === theDate.getMonth()) ) {
            if ( (now.getDate() === theDate.getDate()) && (now.getHours() === theDate.getHours()) ) {
                if ( now.getMinutes() === theDate.getMinutes() && (now.getSeconds() === theDate.getSeconds()) ) { alert("its Time for "+timers[i][1]); stopCheck(i); }
            }
        }
    }
   }, 10);
}

 function stopCheck(i) { clearInterval(timeCheck); }
james emanon
  • 11,185
  • 11
  • 56
  • 97
  • The first one is not working. The second one is giving me an alert for the first element in the array but after that its not giving any alert. (i,e for the second element in the array its not giving the alert) – user1846348 Feb 26 '13 at 22:29
0

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.

Demo: jsFiddle

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>
ThinkingStiff
  • 64,767
  • 30
  • 146
  • 239
  • I dont want to loop through the array every time. The array is already sorted (i,e the first element should be the first to alert, second element will be the next so on) but the only problem is ,it should alert only when the current time matches the time in the array. – user1846348 Feb 26 '13 at 22:37
  • @user1846348 It doesn't make much sense to create that many timers. Why not just `.shift()` and skip the `for()` loop altogether. I updated my answer. – ThinkingStiff Feb 26 '13 at 22:45