Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preferred way to poll a local value in Javascript?

For example, there is a variable called animationComplete (from a 3rd-party library) and a function called happenAfterAnimation:

A simple solution looks like this:

while(!animationComplete) {
   // Do nothing
}
happenAfterAnimation()

Or a more complex solution like this:

function tryHappenAfterAnimation() {
  if(animationComplete) {
    happenAfterAnimation()
  } else {
    setTimeout(tryHappenAfterAnimation, 100)
  }

}
setTimeout(tryHappenAfterAnimation, 100)

The first solution may have some overheads, and the second solution looks a bit dirty.

As future/promise is not available in current version of Javascript, it way may be a bit overkill here.. I was just wondering whether there is an elegant and lightweight way for this situation..

Does anyone have ideas about the better way to deal with this? Thanks!

like image 241
Hanfei Sun Avatar asked May 26 '15 06:05

Hanfei Sun


People also ask

How do you poll in Javascript?

Our poll function is a higher-order function that returns a function, executePoll . The executePoll function returns a promise and will run recursively until a stopping condition is met. The poll function takes 4 variables as arguments: fn : This is the function we will execute over a given interval.

What is poll in node JS?

Long polling in Node JS is a mechanism in which the client sends data to the server, but the server only responds until it has received complete data. Simultaneously, the client's link is open, and it is waiting for the server to reply with data before sending another query.


1 Answers

The first approach will not work at all. It will block the thread forever.

The absence of built-in promise support isn't really an excuse not to use promises. If your library gives you an event/callback-driven way to wait on the results (and I would be surprised if it didn't), then you should use an event, or promises.

If not, and polling the variable is really your only option, then I would say your second approach is pretty much the only option.

like image 192
JLRishe Avatar answered Sep 22 '22 02:09

JLRishe