admin管理员组文章数量:1287584
I need to do the equivalent of this in javascript:
while (typeof someObject == 'undefined') {
sleep(10); // 10ms
}
And I just can't quite figure out how to code this.
I have this:
function sleep(ms, callback, arg) {
setTimeout(function() {
callback(arg);
}, ms);
}
function waitForDef(elem) {
if (typeof elem == 'undefined') {
sleep(10, waitForDef, elem);
}
}
But it's not clear to me how to use this from my code.
I need to do the equivalent of this in javascript:
while (typeof someObject == 'undefined') {
sleep(10); // 10ms
}
And I just can't quite figure out how to code this.
I have this:
function sleep(ms, callback, arg) {
setTimeout(function() {
callback(arg);
}, ms);
}
function waitForDef(elem) {
if (typeof elem == 'undefined') {
sleep(10, waitForDef, elem);
}
}
But it's not clear to me how to use this from my code.
Share Improve this question edited May 22, 2014 at 17:34 Larry Martell asked May 22, 2014 at 17:31 Larry MartellLarry Martell 3,7567 gold badges43 silver badges80 bronze badges 5-
2
Wherever your code is defining
someObject
, you should also accept a callback function, which you invoke after you define the variable. You probably should just pass the value directly to the callback, instead of sharing state with a global variable as well. – user229044 ♦ Commented May 22, 2014 at 17:34 - Sounds like you're looking for promises. – Etheryte Commented May 22, 2014 at 17:34
- @meagar: exactly. you should use a callback function – sjkm Commented May 22, 2014 at 17:35
- 1 This is usually a symptom of bad code design. What are you actually trying to do? Why do you need to wait for this element to exist? Why doesn't it exist immediately? What is creating it? When it is being created? Why is it being created? What do you intend to do with it once it exists? – Kevin B Commented May 22, 2014 at 17:36
- After my page is loaded I need to call a js function that will only exist some time after a table gets given a certain class. When I try to call that function from an onload function it fails most of the time because the table does not yet have the class. If I call that function from a setTimeout that waits 1 second it works 99% of the time. I'd like to just wait until the class gets put on the table and the function exists and then call it. – Larry Martell Commented May 22, 2014 at 17:41
1 Answer
Reset to default 10Have an interval running that keeps checking on the element:
var interval = setInterval(function() {
// get elem
if (typeof elem == 'undefined') return;
clearInterval(interval);
// the rest of the code
}, 10);
本文标签: How to wait for an element to be defined in javascriptStack Overflow
版权声明:本文标题:How to wait for an element to be defined in javascript? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741286079a2370277.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论