1. Refactoring
First of all, return inside .each callback does not work. It just interrupts the current iteration, not the whole loop. If you want to break the loop, you should use the simple for-loop and break statement. Then I would recommend calling $() as little as possible, because this one is expensive . Therefore, I would suggest the following refactoring for your function:
function run() { container.find('.roll-user-row[data-user-id="' + user_data.id + '"]').remove(); var children = container.children(); for (var i = 0; i < children.length; i++) { var betContainer = $(children[i]); // to cache children[i] wrapping var itemAmount = betContainer.attr('data-amount'); var betId = betContainer.attr('data-user-id'); if (itemAmount < betData.totalAmount) { $(template).insertBefore(container); return; // instead of "break", less code for same logic } } container.prepend(template); // would not be executed in case of insertBefore due to "return" }
2. Throttling
To start the 50ms repetition process, you use something like setInterval(run, 50) . If you need to be sure that run is running and this is a 300 ms delay, you can only use setInterval(run, 300) . But if the process is initialized in such a way that you cannot change, and 50 ms is a fixed interval for this, then you can protect the run lodash throttle call or the jquery throttle plugin :
var throttledRun = _.throttle(run, 300);
setInterval , for example, you need to replace the original run with the throttle version ( throttledRun ) in the repeater initialization logic. This means that run will not be executed until an interval of 300 m has passed from the previous run .
dhilt source share