gpt4 book ai didi

javascript - 获取定期调用的函数

转载 作者:行者123 更新时间:2023-12-02 22:56:33 25 4
gpt4 key购买 nike

我试图每 5 秒显示一次控制台日志,并且我正在使用此 javascript 代码(用于 chrome 扩展)

let t = document.getElementsByClassName('annonce_titre');
for (elt of t ){
let titleLink = elt.getElementsByTagName('a');
console.log(titleLink[0].href);

setInterval(function(){console.log("Interval reached");}, 5000);
}

但它一次显示所有消息,没有 5 秒的间隔,有人知道这是为什么吗?

最佳答案

(已编辑)
由于您明确表示要为每个 elt 记录一些内容,因此这里有一个解决方案,它使用全局 count 变量来跟踪日志记录函数被调用的次数:

// Defines global variables
var t = document.getElementsByClassName('annonce_titre');
var count = -1;

// Calls logNextTitle at intervals (and gives it a name so we can clear it later)
var logger = setInterval(logNextTitle, 2000);


// The rest of the code defines our functions
function logNextTitle(){

// Increments the global `count` variable
count++;

// Checks whether all the selected elements have been logged
if(count < t.length){

// Gets the title text and logs it
const elt = t[count];
const title = elt.getElementsByTagName('h2')[0];
console.log(title.innerHTML);
}
else{

// Calls clearLogger so we don't keep calling `logNextTitle` forever
clearLogger();
}
}

function clearLogger(){

// Stops the `setInterval` code associated with the identifier `logger`
clearInterval(logger);
console.log("No more titles to log");
}
.annonce_titre{ background-color: green; }
<div class="annonce_titre">
<h2>Title 1</h2>
<a href="https://example.com">example.com</a>
</div>

<div class="annonce_titre">
<h2>Title 2</h2>
<a href="https://example.com">example.com</a>
</div>

<div class="annonce_titre">
<h2>Title 3</h2>
<a href="https://example.com">example.com</a>
</div>

关于javascript - 获取定期调用的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57954893/

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