Question

I want to know the difference between setInterval() (or) setTimeout() in DOM and polling in ajax. What is the main difference? If both are same, why the identified by two different names?

What is mean by polling in AJAX?

Any links or resource about this question would be more appreciative at the moment!!!

Was it helpful?

Solution

setInterval sets a repeating timer, setTimeout sets a timer that fires only once. Polling is when you repeatedly ask for something instead of waiting to be notified. Sometimes polling is necessary, for example if there's no way to be notified -- and this is often the case in Ajax applications. Both setInterval and setTimeout can be used to implement polling, depending on what you want to do.

In the case of periodically making a request to a server it's advisable to use setTimeout instead of setInterval. In the callback you do the request, wait for the response then set a new timer using setTimeout. If you use setInterval and the request latency is comparable to the interval then you risk that the responses will come out of order. For example, the timer fires and you make a request, it takes a little longer than usual so before it has returned the timer fires again, so you make a new request. Now you are waiting for two requests. It would have been better to wait for the first request to come back before doing the second.

OTHER TIPS

polling is when you periodically ping the server to see if something is ready. A user might have made a request that will take some unspecified amount of time, but too long to wait, so you poll the server every x seconds to see if the result is ready.

setTimeout executes a function after the specified interval.

setInterval repeatedly executes a function every time.

check out http://www.w3schools.com/js/js_timing.asp

You can use these two functions to implement a polling scheme, but they are definitely not the same as polling.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top