如何暂停此setInterval函数?

时间:2015-02-28 09:05:37

标签: javascript jquery

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

$.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(),但我不确定如何。

1 个答案:

答案 0 :(得分:1)

如下所示使用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");