Javascript setInterval完成后如何传递变量?
我有以下代码。我开始的小提琴是我尝试做的事情的一个孤立版本Javascript setInterval完成后如何传递变量?,javascript,jquery,Javascript,Jquery,我有以下代码。我开始的小提琴是我尝试做的事情的一个孤立版本 var height; var count = 0; var setHeight = setInterval(function() { count++; console.log('count'); if ( count > 10) { console.log('done'); height = 20; clearInterval(setHei
var height;
var count = 0;
var setHeight = setInterval(function() {
count++;
console.log('count');
if ( count > 10)
{
console.log('done');
height = 20;
clearInterval(setHeight);
}
},100);
console.log('this is the height -> ' + height);
我期望(或希望发生)的是height=20的值要在my console.log中输出的代码>。最终目标是在清除间隔后从我的setInterval函数中检索变量
现在我得到。。这是高度->未定义
小提琴:
我正在努力实现的目标:
所以根本的问题是这个。我有一个在DOM中加载某些元素之前运行的函数。所以我要做的是一直运行函数,直到该元素的实例存在。一旦发生这种情况,我打算得到该元素的高度,并将其传递给另一个变量。我不确定这是否能解决我的问题,但我想如果我能让它工作,我至少可以测试它。
控制台输出为
(11) count
done
this is the height -> 20
在使用jQuery时,还可以使用$.Deferred
// wait for 3 + (0..2) seconds
setTimeout(function () {
$(document.body).append($("<strong>hello</strong>"));
}, 3000 + 2000 * Math.random());
function waitFor(test, interval) {
var dfd = $.Deferred();
var count = 0;
var id = setInterval(function () {
console.log(count++);
var val = test();
if (undefined !== val) {
clearInterval(id);
dfd.resolve(val);
}
}, interval);
return dfd.promise();
}
function waitForEl(selector, interval) {
return waitFor(function () {
var els = $(selector);
return (els.length > 0) ? els : undefined;
}, interval);
}
waitForEl("strong", 100).then(function (strong) {
console.log(strong, strong.height());
});
//等待3+(0..2)秒
setTimeout(函数(){
$(document.body).append($(“hello”);
},3000+2000*Math.random());
函数waitFor(测试,间隔){
var dfd=$.Deferred();
var计数=0;
变量id=setInterval(函数(){
console.log(count++);
var=test();
如果(未定义!==val){
清除间隔(id);
解决方案(val);
}
},间隔);
返回dfd.promise();
}
函数waitForEl(选择器,间隔){
返回waitFor(函数(){
变量els=$(选择器);
返回(els.length>0)?els:未定义;
},间隔);
}
waitForEl(“strong”,100)。然后(函数(strong){
console.log(strong,strong.height());
});
.setInterval将代码的执行延迟指定的毫秒数。在该延迟期间,其余代码将继续执行。这就是为什么在console.log中未定义高度的原因。它是在调用它的代码(console.log)运行100毫秒后定义的。@CoryDanielson,你删除的答案就是我要找的。@krisholenbeck by elements你是说图像吗?(图像加载时间)。还是纯元素?您可以考虑编写一个函数,该函数在条件成功时接受回调函数。这基本上是异步行为。我所说的元素是指一组带有类的
。外部高度
不会改变,因为您似乎将高度作为一个函数参数进行隐藏。实际上,第一个console.log
将打印undefined
@PaulGrime你是对的,我不知道函数参数是从哪里来的;)远离的。谢谢你指出这一点。
(11) count
done
this is the height -> 20
// wait for 3 + (0..2) seconds
setTimeout(function () {
$(document.body).append($("<strong>hello</strong>"));
}, 3000 + 2000 * Math.random());
function waitFor(test, interval) {
var dfd = $.Deferred();
var count = 0;
var id = setInterval(function () {
console.log(count++);
var val = test();
if (undefined !== val) {
clearInterval(id);
dfd.resolve(val);
}
}, interval);
return dfd.promise();
}
function waitForEl(selector, interval) {
return waitFor(function () {
var els = $(selector);
return (els.length > 0) ? els : undefined;
}, interval);
}
waitForEl("strong", 100).then(function (strong) {
console.log(strong, strong.height());
});