Reputation: 7704
In a web app which I'm building, I have two loosely related bits of code running in two separate timers every one second.
I'm looking to optimize the Javascript, is it worth merging these two timers into one or is that just over the top?
Realistically, am I going to increase any performance (considering that we don't know what sort a system a visitor is running ) by merging two 1 second intervals into one 1 second interval?
As I understand it, JavaScript is single threaded so the more things happening, the more these stack up and block other things from happening (timers especially). I just don't know whether one measly timer running every second is an issue at all.
The reason for keeping the two timers separate would purely be code readability, which is fine on the server side where you control the hardware but I don't know what sort of browser or hardware my visitors will be running.
Thanks.
Upvotes: 3
Views: 1326
Reputation: 8694
I would bet that you'd increase performance by eliminating clock handling at the JS level. You certainly won't degrade performance and, with just one timer running, I'd think that you'd enhance code maintainability, if not readability. In the app I'm working on right now, I have one timer running to handle three tasks: a special kind of scrolling, changing the background image of perhaps 300 cells, and checking to see if it's time to refresh the page and issuing an AJAX request if so. That timer is running with a 1/10-sec interval and things are tight, for sure, but the code gets through all of those jobs, once in a while with one clock tick coming on top of the previous.
So I doubt you'll have any trouble with a 1-sec interval and just one tick handler.
Upvotes: 1
Reputation: 39649
In terms of the overall number of operations that can be completed, no, there isn't going to be a measurable difference. It is possible for there to be a perceived performance advantage in keeping multiple timers, however. The more code you have running synchronously in a single timer iteration, the longer all DOM updates and certain types of user interactions are "halted". By splitting these up into multiple timers, you allow other updates to take place in between timer iterations, and therefore the user gets a "smoother" experience.
Odds are in this case there won't even be a difference in perceived performance either, though, so I'd do it whichever way makes the code organization simpler.
Upvotes: 3
Reputation: 12608
If performance really is an issue you could just create 1 timer, and for example use that to call both functions:
function update()
{
A(); //Do your first task
B(); //Do the second
setTimeout("update()", 1000);
}
update();
However, how sure are you that the bottleneck is within this timer? Try to measure first, and dont optimise the wrong parts of your application.
Upvotes: 1