I have an infinity scroll style page I'm working on, (for an example of infinity scroll, click here and scroll down) which runs a function called update()
every time the user scrolls, among other things.
I could use setInterval
instead and check every x millis, however with a timeout that calls itself, the page responds quicker and more reliably.
Basically, update()
adds some content to the page, then, if that content isn't enough to let you scroll down more, sets a timeout to call update()
again. If you only scrolled one pixel, this would be fine, but of course, when you scroll it sends tens or hundreds of scroll events. This bees a problem because there will be tens (or hundreds) of timeouts running at once. Having too many timeouts kills the consistent animation of adding new content I was going for.
So I wanted to check for if a timeout was already waiting to execute using the ID I had, however there doesn't seem to be a function for this is JavaScript. Is there a way to check whether a timeout ID has executed yet or not? If not, are there alternatives? I have JQuery.
...Or should I just make an interval and sacrifice the responsiveness?
I have an infinity scroll style page I'm working on, (for an example of infinity scroll, click here and scroll down) which runs a function called update()
every time the user scrolls, among other things.
I could use setInterval
instead and check every x millis, however with a timeout that calls itself, the page responds quicker and more reliably.
Basically, update()
adds some content to the page, then, if that content isn't enough to let you scroll down more, sets a timeout to call update()
again. If you only scrolled one pixel, this would be fine, but of course, when you scroll it sends tens or hundreds of scroll events. This bees a problem because there will be tens (or hundreds) of timeouts running at once. Having too many timeouts kills the consistent animation of adding new content I was going for.
So I wanted to check for if a timeout was already waiting to execute using the ID I had, however there doesn't seem to be a function for this is JavaScript. Is there a way to check whether a timeout ID has executed yet or not? If not, are there alternatives? I have JQuery.
...Or should I just make an interval and sacrifice the responsiveness?
When the function fires, clear the interval and set the variable you're holding the initial in to null. Then check for a null value. If you're doing a bunch of these, you could store them in an array by the id you have.
eg:
var intervals = [];
if(intervals[id] != null){
intervals[id] = setTimeout(some_func, 1000);
var some_func = function(){
// do stuff
clearTimeout(intervals[id]);
intervals[id] = null;
}
}