0

I 'm invocate sqs.receiveMessage(receiveParams, function(err, data){}) inside an infinite loop. But it didn't get triggered at all.

var receiveParams = { QueueUrl: queueUrl, VisibilityTimeout: 40 }; while (true) { console.log("before"); setTimeout(function() { sqs.receiveMessage(receiveParams, function(err,data){ console.log("Calling"); if (err) { console.log(err); } else { console.log(data); if (data.Messages != null) { console.log("Executing my fuction"); myFunction(); } } }); }, 10000); console.log("after"); } 

If I execute sqs.receiveMessage() outside the loop, it works fine. I don't know why it never gets invocated in the loop. I'm guessing there is something wrong with my timeout settings. Because my loop will log "before" and "after" without time delay. Any Help?

1 Answer 1

2

Your code is flooding the node event stack with infinite amount of setTimeout commands.

That is, on code run it will first spawn a task to do the sqs.receiveMessage call - which it will do it a second later. However before the 1st task is set off, on the second iteration of your while loop it will again spawn another similar task. So within a second's time frame you will have like a thousand of those tasks which are probably 1 milliseconds apart to set off. This explains why you are see'ing the prints.

The reason why you ain't getting a proper response from the service could be that it has "flood protection" enabled. E.g. if there are too many requests within a certain time from the same caller then it will ignore the caller for X amount of time.

You might want to use setInterval instead.
See https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setInterval

setInterval
Repeatedly calls a function or executes a code snippet, with a fixed time delay between each call. Returns an intervalID.

Example:

// repeat the call every 10seconds setInterval(function() { sqs.receiveMessage(receiveParams, function(err,data){ console.log("Calling"); if (err) { console.log(err); } else { console.log(data); if (data.Messages != null) { console.log("Executing my fuction"); myFunction(); } } }); }, 10000); 

Let me know how you go with it. Happy to help further, if required.

Sign up to request clarification or add additional context in comments.

2 Comments

Your explanation is correct, but an 'async' loop might be a better solution in my case.
@LingboTang - Glad the explanation helps and eventually got you onto a even better solution.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.