setTimeOut和输入效果[重复]

问题描述 投票:0回答:2

这个问题在这里已有答案:

我目前正在遇到这个问题,我想在这个例子中慢慢显示一个词我希望显示“你好我的名字是......”但它应该像那样记录:

然后500毫秒后“H” “他”然后500毫秒后 然后“Hel”...... “地狱”等......

但所有人都表示感谢您的时间。

    function type(string, length) {
        if(length < string.length+1) {
            console.log(string.slice(0, length), length);
            setTimeout(type(string, length+1), 500);
        }
    }
    
    type("hello my name is...", 1);
javascript settimeout
2个回答
2
投票

发生这种情况是因为您不是将函数作为参数传递,而是在参数的位置上调用函数。

您可以使用bind通过参数传递函数的引用。像这样:

function type(string, length) {
        if(length < string.length+1) {
            console.log(string.slice(0, length), length);
            setTimeout(type.bind(null, string, length+1), 500);
        }
    }
    
    type("hello my name is...", 1);

注意到bind上的第一个参数是null。那是因为第一个参数是函数内部的this值。由于它没有使用,你可以使用null


0
投票

问题是你没有将正确的第一个参数传递给setTimeout。它需要一个函数引用作为第一个参数,但是你要传递一个函数调用 - 你要求立即运行type,并且type(在你的情况下是undefined)的返回值被传递给setTimeout()

如果将函数调用包装在函数声明中,问题就解决了。

function type(string, length) {

    if(length < string.length+1) {
        console.log(string.slice(0, length), length);
        timer = setTimeout(function(){type(string, length+1)}, 500);
    }
}

type("hello my name is...", 1);
© www.soinside.com 2019 - 2024. All rights reserved.