javascript - 在 JavaScript 中使用 setInterval 时在函数调用之间等待不同的时间?

标签 javascript angularjs settimeout setinterval

在我的网站上,两个词被一遍又一遍地一个字母一个字母地打印出来。我希望打印的字母之间有 0.1 秒的间隔,当我得到一个完整的单词时,我想等待 3 秒再打印新的字母。我使用了 setTimeout 但它不起作用。我的代码有什么问题?

var app = angular.module("app", []);

app.controller('mainCtrl', function ($scope) {
    var values = ['.com', 'available'];
    var index = 0;
    $scope.comval = '';
    function changeText (){
        if(values[index].length == $scope.comval.length) {
            $scope.comval = '';
            index++;
            if (index >= values.length) {
                index = 0;
            }
        }
        else
        {
            $scope.comval = values[index].substring(0, $scope.comval.length+1);
            $scope.$apply();
            console.log($scope.comval);
        }
    }

    setInterval(changeText,100);
});  

效果可以在this上看到地点。请看下图中描绘的部分:

enter image description here

JSFiddle .

最佳答案

为了解决这个问题,我使用了setTimeout(在指定时间后调用函数一次)而不是setInterval(调用函数一遍又一遍)再次)。因为我们希望它不只被调用一次,所以我们将对 setTimeout 的调用放在函数 (changeText) 中,以便它添加一个计时器来调用自身。这让我们可以针对不同的情况使用不同的延迟 - 当我们刚刚打印一个新字母时为 100 毫秒,当我们完成一个新单词的打印时为 3000 毫秒。

var app = angular.module("app", []);

app.controller('mainCtrl', function ($scope) {
    var values = ['.com', 'available'];
    var index = 0;
    $scope.comval = '';
    function changeText (){
        if(values[index].length == $scope.comval.length) {
            $scope.comval = '';
            index++;
            if (index >= values.length) {
                index = 0;
            }
            //We have printed a full word!
            //Wait 3000 ms to call the function again.
            setTimeout(changeText,3000);
        }
        else
        {
            $scope.comval = values[index].substring(0, $scope.comval.length+1);
            $scope.$apply();
            console.log($scope.comval);
            //We have printed only a letter.
            //Just wait 100 ms before calling the function again.
            setTimeout(changeText,100);
        }
    }

    //Start it all off.
    setTimeout(changeText,100);
});

Fiddle .

关于javascript - 在 JavaScript 中使用 setInterval 时在函数调用之间等待不同的时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33412930/

相关文章:

javascript - 如何求和已检查更改的复选框 jquery 的值?

javascript - href 内的输出变量 - Javascript

javascript - 适用于 JavaScript Web 应用程序的 AWS Cognito。如何检查 Cognito token 是否已过期

php - 来自PHP服务器的AngularJS流音频

javascript - Angular2 中 Angular 的 $q 等价于什么?

javascript - Protractor 中的 setTimeout 替代方案

JavaScript instanceof 运算符返回 false

c# - 如何将 sql 表中的多列分配给 List<> 中的单列

javascript - 倒数计时器脚本中跳过了很多秒

javascript - 延迟显示 forEach 循环中的数组元素