Reputation: 2027
I have this question that came up while working on my current project.
I have a table with a bunch of data that can be modified by the user. According with the modifications performed, a series of boxes updates the information they show (budget calculation, estimated price, things like that).
I thought 2 ways of tackling that.
One is using the setInterval
function. Every, let's say half second, the function that reads all data in the table to update the boxes will be triggered.
The second approach is by setting an event to the whole page:
$(document.body).on("keyup paste", function() {calculate();});
And I wonder which of this two method is the best approach considering performance. So far I would say the second one, because somehow I'm biased against the use of functions triggered over and over, but my understanding of this matter is quite a bit rudimentary and I could be taking the wrong approach.
Upvotes: 0
Views: 183
Reputation: 1201
You should use an event handler/listener. There's no need to recompute the data when it hasn't been changed - that's needless work the browser is doing. But it certainly doesn't have to be on the entire body. Instead of firing an event based on how the user interacts with the entire page, you can fire an event for when the user interacts with specific elements (the boxes you refer to).
For example, I'll assume you use <input>
fields: you can bind the 'input' event using jQuery to each field and run the computation function each time it fires. See the various answers to this question here for more details.
Attaching an event handler to the body can be useful in some instances, but for your case, appears to only add needless overhead.
The MDN has a page on event listeners in modern browsers - jQuery isn't absolutely necessary for this either.
Upvotes: 0
Reputation: 86
You can try using a javascript debounce function. http://davidwalsh.name/javascript-debounce-function
$(document.body).on("keyup paste", debounce(function() {calculate();}, 100) );
Upvotes: 1
Reputation: 452
Depending on the complexity of the calculate function, I'd say the second option (key event trigger) is probably fine. If there's a lot of calculation going on then you might even want to consider a mixture of key-trigger and setTimeout like so:
var keyTimeoutDelay;
$('body').on('keyup paste', function(){
// Check if a timeout is set, and clear it if so...
if(keyTimeoutDelay) clearTimeout( keyTimeoutDelay );
// Set a timeout to delay the processing by 500ms.
keyTimeoutDelay = setTimeout(function(){
calculate();
}, 500);
});
function calculate(){
// Complex calculation stuff
}
This code will run on keyup event and 'paste' but will only call the calculate() function if there was a delay of 500ms between pressing keys. You can try it out by running your finger along all the keys on your keyboard - the calculate() method will only get called once you stop 'typing'
Upvotes: 2