在JavaScript中使用setInterval时,函数调用之间的等待时间是否不同?
在我的网站上,两个字被一个字母一个字母地反复打印。我希望打印的字母之间的间隔为0.1秒,当我得到一个完整的单词时,我希望在打印新单词之前等待3秒。我使用了在JavaScript中使用setInterval时,函数调用之间的等待时间是否不同?,javascript,angularjs,settimeout,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;
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);
});
这种影响可以在现场看到。请看下图所示的零件:
.像这样使用
$interval
:
$interval(changeText, 100);
另外,不要忘记将$interval
注入控制器
编辑:
由于要在三秒后运行该功能,请使用$timeout
服务:
$timeout(function() {
$interval(changeText, 100)
}, 3000)
再次,在控制器中注入
$timeout
。为了解决这个问题,我使用了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);
});
.$interval与setInterval(changeText,100)相同$间隔是angular自己的服务。如果我这样做,这个函数运行缓慢,但我想用这个速度每3秒调用一次,你说的“缓慢”是什么意思?它将每3秒运行一次。我不明白你的意思…如果我不善于解释,我不想每3秒运行一次,我想每3秒调用一次谢谢,安德斯,你很棒