gpt4 book ai didi

javascript - 运行一个函数,每 50 毫秒调用一次自身,并在条件为真时返回值

转载 作者:行者123 更新时间:2023-12-02 16:11:02 24 4
gpt4 key购买 nike

我想要一个代码能够知道是否存在某些 html 元素。我在超时内使用递归调用。也许可以是另一种方法,但我有兴趣知道如何编写这段代码。

if (exist("an_id")!==null)
{ ..... }

function exist (id)
{ times =20;
var el;
function get_el (callback)
{
el = document.getElementById(_id);
if (el==null )
{
if (--times==0)
callback();
else
setTimeout( function () {get_el()}, 50);
}
else
callback();
}
get_el ( function (){return el;}); // first call. pass callback.
}

这段代码显然运行正常,在指定的“时间”之后是否检测到“el”,但函数“exist”不返回任何内容。

我有些困惑。任何帮助将不胜感激。-

最佳答案

嗯,你不能只使用 return value of a synchronous method 。您的条件将始终评估为 false。

您可以将其封装在一个返回 Promise 或接受回调的函数中:

function exists(id){
return new Promise(function(resolve, reject){ // old browsers need polyfill
setTimeout(function check(){
if(document.getElemenyById(id)) resolve();
else setTimeout(check, 50);
}, 50);
});
}

这会让你这样做:

exists("someID").then(function(){
// here the element exists
});

关于javascript - 运行一个函数,每 50 毫秒调用一次自身,并在条件为真时返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30209908/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com