3

I am using angular $timeout as,

 $scope.alltexts = ["hii" , "hello" , "hehe"]
 var sendtime = 60000

 for (var i = 0; i < $scope.alltexts.length; i++) {
   var text = $scope.alltexts[i]
   $setTimeout(function() {}, (function(){$scope.addtext(text)}, sendtime + (i * 60000)));
 };

 $scope.addtext = function(text){
  console.log(text)
 }

But after each one minute it only console "hehe". Means it considers only last value. Please let me know how should I get proper results.

1

2 Answers 2

2

Too much of closures today, you are always passing the last index... a closure will create a new scope for each iteration.

 $scope.alltexts = ["hii" , "hello" , "hehe"]
 var sendtime = 60000

 for (var i = 0; i < $scope.alltexts.length; i++) {
   (function(i){
   var text = $scope.alltexts[i]
   $setTimeout(function() {}, (function(){$scope.addtext(text)}, sendtime + (i * 60000)));
   })(i)
 };

 $scope.addtext = function(text){
  console.log(text)
 }
Sign up to request clarification or add additional context in comments.

Comments

1

Try this

$scope.alltexts = ["hii" , "hello" , "hehe"]
 var sendtime = 60000

 for (var i = 0; i < $scope.alltexts.length; i++) {
   (function(i){
   var text = $scope.alltexts[i]
   $setTimeout(function() {}, (function(){$scope.addtext(text)}, sendtime + (i * 60000)));
   })(i)
 };

 $scope.addtext = function(text){
  console.log(text)
 }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.