Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run Loop In Background

So, I am needing to run an infinite loop in the background of my app (written in JS) that will be used to cycle a ScrollableView every six seconds. However, while this loop runs, I'm unable to preform any other operations in the app as you would think.

To sum up, how can I run this loop at all times while still making the app operational?

Code:

function startScrolling() {
    for(; ; ) {
        sleep(6000);
        Ti.API.info('Scrolling To Index: ' + viewIndex);
        scrollView.scrollToView(viewIndex);
        if(viewIndex == 4) {
            viewIndex = 0;
            scrollView.scrollToView(viewIndex);
        } else {
            scrollView.scrollToView(viewIndex);
            viewIndex++;
        }
    }
}

function sleep(milliseconds) {
    var start = new Date().getTime();
    while((new Date().getTime() - start) < milliseconds) {
        // Do nothing
    }
}

EDIT: Solution

setInterval(function() {
    Ti.API.info('Scrolling To Index: ' + viewIndex);
        scrollView.scrollToView(viewIndex);
        if(viewIndex == 4) {
            viewIndex = 0;
            scrollView.scrollToView(viewIndex);
        } else {
            scrollView.scrollToView(viewIndex);
            viewIndex++;
        }
}, 6000);
like image 907
JTApps Avatar asked Jun 29 '12 16:06

JTApps


1 Answers

Take a look at window.setInterval().

/* 
    Calls a function repeatedly, with a fixed 
    time delay between each call to that function.
*/
setInterval(startScrolling, 6000);
like image 66
James Hill Avatar answered Sep 20 '22 03:09

James Hill