Reputation: 2284
We are building a web app using Twitter Bootstrap as a framework and have problems showing/hiding tooltips. Apart from trying to find a solution to the actual problem, I have a question regarding the workaround we use in the meantime:
Performance-wise, is it generally a bad idea to use setInterval()?
How can I measure the performance impact caused by this?
Are there better ways to constantly check for the presence of elements and remove them?
// temporary workaround to remove unclosed tooltips
setInterval(function() {
if ( $('.tooltip.in').length > 1 ) {
$('.tooltip').remove();
}
}, 1000);
Upvotes: 4
Views: 6957
Reputation: 5706
if you're really, really worried about performance, using a live nodelist might be faster :
var tooltipInNodes = document.getElementsByClassName("tooltip in");
var tooltipNodes = document.getElementsByClassName("tooltip");
setInterval(function() {
if ( tooltipInNodes.length > 1 ) {
$(tooltipNodes).remove();
}
}, 1000);
This is unlikely to make much of a difference though, and as has been mentioned, using setInterval with long intervals (a second is big, 4ms is small) is unlikely to have any major effects.
Upvotes: 1
Reputation: 1664
This is better to avoid this technic, but until you find a real solution, you can optimize this workaround.
Create a not anonymous function and call it, you'll avoid "context function creation" every second.
You can also optimize jQuery selectors by caching and specify the tag name.
setInterval(tmp_workaround, 1000);
function tmp_workaround() {
var $selectors = $('[TAG IF ALWAYS THE SAME].tooltip.in');
if ( $selectors.length > 1 ) {
$selectors.remove();
}
}
Upvotes: 0