简体   繁体   中英

What's the easiest / most efficient way to pause setInterval while data is loading? JavaScript/Jquery

So i have a JS Interval doing a load command on a script.. and displays the loaded data on a div..

Everything was perfect until i put my project online and saw an issue (in the background)..

Since the setInterval needs to be set at 1 second interval , and a lot of times the time it takes for the data to load is more than 1 second, i see load stacking happening in the background... since the setInterval continues to fire $.load() calls every second regardless of any loaded data..

I was thinking of setting a global variable "is_loading" to add to my function in the interval, to skip the rest of the routine incase "is_loading" is true, .. once the recent load call completes, it sets is_loading = false..

this way the interval keeps firing / second w/o load calls stacking in the background...

however, since i have several intervals doing loads all over the page (pls dont ask why lolz) i find it quite tedious to do this w/ every interval.. therefore i was wondering is there something i can do "globally" like an event listener of some sort for current unfinished loading/get/post happening on the page?

Suggestions would be great

Like others have said, I would use setTimeout to make a new request whenever a request completes.

For dealing with multiple requests on a timer, I recommend making some sort of master timer/scheduler in order to decrease the amount of setTimeouts running all over. This article from Google is was helpful to me when I was doing something similar:

http://googlecode.blogspot.com/2009/07/gmail-for-mobile-html5-series-using.html

There were some great suggestions (and reminders) here, but what I'm going to do is create my own setInterval function that does what i want to do..

myInterval(function,time,hold_variable,attempts) where hold_variable = window.variable issued and checked for before executing the actual function. this is the same variable name my function will set back to 0 when it finishes and allows another call of itself

attempts = optional variable, the count of how many times the interval attempts to call the function unsuccessfully due to the hold_variable..

this is a pretty straight forward solution on the setInterval side.. only inconvenience is that my functions need to "set" each of their hold_variables (a tiny modification on each function)...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM