jQuery - how to call ajax when certain condition is met

I know you can use the function setInterval to call your ajax function at fixed time interval. What I'd like to achieve though is something like this:

while (true) //but obviously this while loop will block other code. I'd like it non-blocking
{   //if certain condition is met, call my ajax function.

so basically the code should sit silently in the background, listening. if certain condition is meet, fire ajax call.

Is is possible in jquery/javascript?

Edit: For conditions: basically, I will be automatically scrolling the rows of a large table (that is another question, another post...), once it reaches the last row, the condition is met, ajax is called to fetch data from the server, re-populate the table, and start automatically scrolling again.


In Javascript, conditions do not "become met" all by themselves.

It's (mostly) a single threaded language, where the UI thread just sits around waiting for events to happen, and in response the programmer supplied event handlers go do stuff. So long as they're doing stuff, the UI thread is unable to handle any more events.

This is why you shouldn't ever use a busy loop, or otherwise tie up the CPU doing long-winded calculations in a tight loop.

In summary, you shouldn't ever need to poll a condition - it should be evident when that condition becomes true because some event will have fired, allowing it to become true.

You should then be able to fire off your AJAX request in that event's handler.

EDIT you've now clarified that you want to do this when the scroll reaches the end of a table.

Per above, there is (of course) an event that tells you that something scrolled, and it'll tell you how far.

Look at http://api.jquery.com/scroll/

You need to register a handler for that event, and then trigger your AJAX call in that handler.

Certainly possible if you have an event. Then you can attach a handler to it. So the question is: what condition ?

Need Your Help

Server rendering with rails + react-rails gem + react router

ruby-on-rails reactjs react-router react-rails server-rendering

I have create this sample repo that use rails (v4.2.6) with react-rails (v1.6.2) and react-router (v2.0.0-rc5): https://github.com/pioz/rails_with_react_and_react_router_example

SVN Prevent Files on Branch from Changes

svn deployment branch branching-and-merging collaboration

I'm trying to develop a branching structure in a project where we have release branches for each environment we release to (QA, Staging, Production). I have created these 3 branches with their