Reputation: 2230
I have c# code that runs a query in SQL and returns roughly 2000 rows. Then a Treeview control is created and added the my main page. This is done almost instantly, which is good.
var orgId = $('select[name="ctl00$PageContent$FunctionsDropDownList"] option:selected').val();
if (!orgId) {
return false;
}
//calls serverside get data
//This line happens quickly
$('#ctl00_PageContent_HiddenRulesDialogTriggerButton').click();
//This part takes about 10-15 minutes to finally get to the true
var i = setInterval(function () {
if ($('#ctl00_PageContent_treeview').find('table').length > 0)
{
clearInterval(i);
StartDialog();
return false;
}
});
So it takes about 10-15 minutes to hit the clearInterval(i)
. When it does, i = 978
. Not sure why it would take so long. Possibly the find()
is really slow. Does anyone recommend an alternative?
EDIT
Upvotes: 6
Views: 111
Reputation: 466
The problem is probably the fact that you are calling setInterval without the second argument (time interval)
Let's look at what your code seems to do.
A couple problems.
Code:
var timer_id = setInterval(function() {
...code here...
});
...I think it executes every millisecond. I've tested this with this code:
var k = 1;
var i = setInterval(function () {
if (k < 100)
{
k += 1;
} else {
clearInterval(i);
window.alert('Finished!');
}
//No second argument
});
...and it finished almost instantly.
So I'm guessing it is going so slow because the program is firing a costly DOM search hundreds of times per second. The solutions are:
Code:
var i = setInterval(function () {
if ($('#ctl00_PageContent_treeview').find('table').length > 0)
{
clearInterval(i);
StartDialog();
return false;
}
//Once per second
},1000);
A callback would be better practice but supplying the time interval will probably work too.
Upvotes: 2
Reputation: 1
Try using .one()
, DOMNodeInserted
event , delegating event to document
.
function StartDialog(el) {
console.log(el)
}
$(document)
.one("DOMNodeInserted"
, "#ctl00_PageContent_treeview table"
, function(e) {
StartDialog(this)
});
$("#ctl00_PageContent_treeview").append("<table></table>")
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<div id="ctl00_PageContent_treeview"></div>
Upvotes: 1