gpt4 book ai didi

javascript - 如何停止这个 setInterval 函数?

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

这个循环永远循环,如何在标记的位置停止它?

$.fn.writeText = function(content) {
var contentArray = content.split(""),
current = 0,
elem = this;
setInterval(function() {
if(current < contentArray.length) {
elem.text(elem.text() + contentArray[current++]);
}
else{
//stop here.
}
}, 100);

};

$("#ID").writeText("Texty text text");

谢谢。我认为它应该是clearTimeout(),但我不确定如何。

最佳答案

使用clearTimeout(),如下所示:-

$.fn.writeText = function(content) {
var timer;
var contentArray = content.split(""),
current = 0,
elem = this;
timer = setInterval(function() {
if(current < contentArray.length) {
elem.text(elem.text() + contentArray[current++]);
}
else{
clearTimeout(timer);
}
}, 100);

};

$("#ID").writeText("Texty text text");

关于javascript - 如何停止这个 setInterval 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28779987/

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