【问题标题】:How do I halt this setInterval function? [duplicate]如何停止这个 setInterval 函数? [复制]
【发布时间】:2015-02-28 09:05:36
【问题描述】:

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

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

【问题讨论】:

标签: javascript jquery


【解决方案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");

【讨论】:

    猜你喜欢
    • 2014-06-18
    • 2021-01-30
    • 1970-01-01
    • 1970-01-01
    • 2010-12-22
    • 1970-01-01
    • 1970-01-01
    • 2020-08-17
    • 1970-01-01
    相关资源
    最近更新 更多