Kuravi H
Kuravi H

Reputation: 111

infinite loop with changing timeouts

I have an array that contains time windows. For a simple case I'm making these 10 second windows as follows, (In the beginning the current time will be inside window 1)

var now = new Date();
windowList = [
    { id: 1,
        start: new Date().setSeconds(now.getSeconds() - 5),
        end: new Date().setSeconds(now.getSeconds() + 5),
        waitTime: 2000},
    { id: 2,
        start: new Date().setSeconds(now.getSeconds() + 10),
        end: new Date().setSeconds(now.getSeconds() + 20),
        waitTime: 500}]

Then I've setup two functions to check if current time is in a window and in some window.

function isInWindow(window){
    var now = new Date();
    return (window.start < now && now < window.end);
}

and

function isInSomeWindow(windows){
    for (var i = 0; i < windows.length; i++) {
        if(isInWindow(windows[i])){
            return windows[i];
            break;
        } else {
            return false;
        }
    }
}

Now I want to go through the windowList as I loop with a period of waitTime. Whenever I'm not in a window I loop with period of 500 ms.

function daynmicRepeat() {
    var localPeriod = 1000;
    setTimeout(function () {
        window = isInSomeWindow(windowList);
        if (window){
            console.log('in window ' + window.id + ' @ ' + new Date())
            localPeriod = window.waitTime;
        } else {
            console.log('not in a window @ ' + new Date());
            localPeriod = 500;
        }
        daynmicRepeat();
    },localPeriod);
}

when I run it

daynmicRepeat()

I start off inside the first window and then eventually come out of it but never seem to go in to the 2nd window. What am I doing wrong?

Upvotes: 1

Views: 85

Answers (2)

zkcro
zkcro

Reputation: 4344

Take another look at the loop in your isInSomeWindow function -- it will never get past the first run:

if(isInWindow(windows[i])){
    return windows[i];
    break;
} else {
    return false;
}

If isInWindow(windows[0]) returns false, you hit the else statement, and return out of the function.

Assuming you want the function to return false if no matching window is found, you want to return if the loop finished without returning:

function isInSomeWindow(windows){
    for (var i = 0; i < windows.length; i++) {
        if(isInWindow(windows[i])){
            return windows[i];
            break;
        }
    }
    return false;
}

Upvotes: 1

Malk
Malk

Reputation: 11983

isInSomeWindow breaks the loop. Try this:

function isInSomeWindow(windows){
    for (var i = 0; i < windows.length; i++) {
        if(isInWindow(windows[i])){
            return windows[i];
    }
}

Upvotes: 1

Related Questions