如何在 setInterval 完成后传递变量

How to pass a variable after setInterval completes?

本文关键字:变量 setInterval      更新时间:2023-09-26

我有以下代码。我开始的小提琴,这是我正在尝试做的事情的孤立版本。

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;的值.log。最终目标是在清除间隔后从我的 setInterval 函数中检索变量。

现在我得到..这是高度 ->未定义

小提琴:

http://jsfiddle.net/GNvG6/8/

我正在努力完成什么:

所以根本问题是这个。我有一个函数,可以在 DOM 中加载某些元素之前运行。所以我要做的是继续运行该函数,直到该元素的实例存在。一旦发生这种情况,我打算获取该元素的高度并将其交给另一个变量。我不确定这是否会解决我的问题,但我想如果我能让它工作,我至少可以测试一下。

var height;
var count = 0;
var setHeight = setInterval(function() {   
    count++;
    console.log('count');
    if ( count  > 10)
    {
        console.log('done');
        height = 20;
        reportHeight(height);
        clearInterval(setHeight);   
    }
},100);
function reportHeight(height){
    console.log('this is the height -> ' + height);
}

控制台输出为

(11) count
done
this is the height -> 20 

小提琴演示

var height = 0;                                        // initial value
var count = 0;
var setHeight = setInterval(function() {   
    count++;
    console.log('count and height is still:'+ height); // height is always 0
    if ( count  > 10){
        height = 20;
        console.log('done and height is:'+ height);    // height is finally 20
        clearInterval(setHeight);           
    }
},100);

当你使用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());
});

这个jsfiddle中的例子。