在我的网站上,两个词被一遍又一遍地一个字母一个字母地打印出来。我希望打印的字母之间有 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上看到地点。请看下图中描绘的部分:
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/