To add dynamic content to an existing page from a database as the user scrolls, you can make an AJAX call on scroll and control the number of calls using a throttle function. This function will ensure that the AJAX call is only served a maximum of once within a specified wait time interval.
var myajax = _.throttle(/*your ajax call goes here*/, wait/*time in ms*/);
The _.throttle() function is part of the underscore.js library. If you prefer not to use this library, you can utilize a custom version of throttle:
function myThrottle(func, wait, leading) {
var lastCall = 0, timeout = null,
execute = function() {
clearTimeout(timeout);
timeout = null;
func();
};
return function() {
var currentTime = new Date().getTime();
if (leading && (lastCall == 0 || (currentTime - lastCall) > wait)) {
lastCall = currentTime;
func();
}
else if (!leading && !timeout)
timeout = setTimeout(execute, wait);
};
}
In the above snippet, the third argument leading determines whether the call should be made at the beginning or end of the wait duration. Setting it to true triggers the call at the start, blocking further calls until the wait period ends.