2015-10-29 57 views
1

我的网站上两句话正在被打印逐个字母一遍又一遍。我希望在打印的字母之间有0.1秒的时间,当我得到一个完整的单词时,我想等3秒钟才能打印新的单词。我用setTimeout但它不工作。我的代码有什么问题?在JavaScript中使用setInterval时等待函数调用之间的不同时间?

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

回答

2

为了解决这个问题,我用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

+0

感谢百万安德斯,你太棒了 – sani

0

使用$interval这样的:

$interval(changeText, 100); 

另外,不要忘记注入$interval到控制器中。

编辑:

既然你想运行的功能三秒之后使用$timeout服务:

$timeout(function() { 
    $interval(changeText, 100) 
}, 3000) 

再次,在控制器注入$timeout

+0

$间隔是在使用setInterval相同的(changeText,100); ? – sani

+0

$ interval是angular自己的服务。 –

+0

确定,但每3秒,我想调用这个函数 – sani

相关问题