如何停止此setInterval函数

How do I halt this setInterval function?

本文关键字:函数 setInterval 何停止      更新时间:2024-06-26

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

$.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");