Avoiding Infinite Loops

akalsey -

When your Tropo application contains a loop, it is important to not get the application stuck in a state where the loop will never complete. In web programming, doing this will usually just cause your web server to throw an error. In desktop programming, you can usually just stop your code execution by killing your application. However, in Tropo the session will run forever, consuming resources and possibly repeating a call or text message until Tropo support kills your application. If it's a repeated issue, Tropo may lock your account without any notice to protect our network.

The simplest version of an infinite loop is this JavaScript code.

while(true) {
  call('sip:alice@example.com');
  say('are we there yet?');
}

This will never complete, and will cause Tropo to call alice@example.com and say 'are we there yet' over and over again.

One thing we see often are applications that are looking for input inside of a loop, but when the caller hangs up, the application keeps looping.

var number = null;
while(response == null) { var result = ask('What is your account number?', {choices: '[8 DIGITS]'});
if (result.choice) { number = result.value;
} else {
say('Sorry, I didn't get that.');
} }

If the caller hangs up before entering an account number, then number will never be updated to anything other than null, and the while loop will never end.

To avoid this loop, Tropo provides an isActive() function that returns the current state of the call. If the caller is still connected, it returns True. If they've hung up, it returns false. So change your loop to read

var number = null;
while(response == null && currentCall.isActive()) { var result = ask('What is your account number?', {choices: '[8 DIGITS]'});
if (result.choice) { number = result.value;
} else {
say('Sorry, I didn't get that.');
} }

Now, your loop will only continue if the caller hasn't entered an account number and the caller is still connected. Once the call ends, the loop will break and your script will end normally.

Make sure to add isActive() to all of your loops, and strive to avoid loops that cannot complete. Check your looping logic to ensure that there is no state the application can get into where it cannot leave the loop. Place count limits on your loops, don't rely on user input to break a loop, and avoid "while(true)" loops.

Have more questions? Submit a request

0 Comments

Article is closed for comments.