grasshopper
grasshopper

Reputation: 948

How to Long Poll in NodeJS / Javascript?

Just to be clear my understanding of long polling is that you make request to a server on a time interval.

I am trying to implement a bitcoin purchasing system that checks the blockchain for change in my wallets balance. I know there are websockets that do this but I have to wait for 1 confirmation to receive an update and the REST API offers more flexibility, so I would just prefer to make a request to the server every 5 seconds or so and check each response for a change in my balance then go from there.

The issue is I can't seem to figure out how to do this in NodeJS. Functionially this is how I imagine my code.

Get current balance (make request)
Get current balance again (make request)
Check if there is a difference
**If not** 
  wait 5 seconds
  Get current balance
  Check for difference
  repeat till different (or till timeout or something)
If different
do some functions and stop checking balance.

I've been trying to do each step but I've gotten stuck at figuring out how to create a loop of checking the balance, and stopping the loop if it changes.

My original thought was to use promises and some for loops but that doesn't materialize.

So now I am asking for your help, how should I go about this?

Upvotes: 1

Views: 1671

Answers (1)

Yousef
Yousef

Reputation: 401

One way to do this would be to setup a setInterval timer to kickoff a request every x seconds. By setting some logic after the response you can then choose to de-reference the timer and trigger another function. Here's a snippet. You'll notice I set a variable to reference the timer, and then de-reference it by setting it to null, where then the GC is smart enough to release. You may also use the 'clearTimeout' function, which is perhaps the better way to go.

Upvotes: 1

Related Questions