0

我有:

var c = {
    typeStart: function(msg, loc) {
        loc.append("<p>");
        this.typeLetter(msg, loc, 0);
    },

    typeLetter: function(msg, loc, pos) {
        loc.append(msg.charAt(pos));
        pos = pos + 1;
        if (pos == msg.length) { this.typeEnd(loc); }
        setTimeout(this.typeLetter(msg, loc, pos), 100);
    },

    typeEnd: function(loc) {
        loc.append("</p>");
    }
}

c.typeStart("hello", $("#somediv"));

出于某种原因,我显然遗漏了一些东西,typeLetter被无限调用。我认为这与 javascript 的异步特性有关。

4

1 回答 1

4

这是你的问题:

typeLetter: function(msg, loc, pos) {
    loc.append(msg.charAt(pos));
    pos = pos + 1;
    if (pos == msg.length) { this.typeEnd(loc); }
    setTimeout(this.typeLetter(msg, loc, pos), 100);
},             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

将调用此函数并将结果传递给setTimeout. 您需要将其包装在一个匿名函数中:

setTimeout(function() {
    this.typeLetter(msg, loc, pos);
}, 100);
于 2013-04-30T00:28:32.657 回答