0

Why am I getting a 'syntax error: unexpected identifier' and why does my browser gets stuck in a continuous loop after I run this code? I'm using setInterval to delay the requests to the API per the API request guidelines.

var tempArray = []; 
var arr = [];   
//angular controller    
for (var i = 0; i < 10; i++) {
    setInterval($http.get(url).success(function(data) {
        tempArray.push(data);
        arr.push(tempArray);
    }), 1000);
}
3
  • Where are you getting "unexpected identifier"? Also, if you want to delay a request, you probably want setTimeout - using setInterval will continually call the supplied function every 1 second. Commented Oct 21, 2016 at 21:41
  • AngularJS apps should use the $timeout service for delays because it properly integrates window.setTimeout with the AngularJS framework. For more information, see AngularJS $timeout Service API Reference; Commented Oct 21, 2016 at 21:57
  • Either way, both $timeout and window.setTimeout require the first argument be a function. The $http service returns a promise object. Commented Oct 21, 2016 at 22:02

2 Answers 2

2

As @vlaz has explained, you want setTimeout if you want to "delay" something. setInterval will continually call the supplied callback.

I'm a little confused why the API guidelines say to "delay" requests though... do they mean "debounce"?

Either way... the "unexpected identifier" syntax error will be because you are not passing a function as the first argument to setInterval. You need:

setTimeout(function() {
  $http.get(url).success(function(data) {
    tempArray.push(data);
    arr.push(tempArray);
  });
}, 1000);

$http.get(url).success() does not return a function that setTimeout can call so you cannot pass it directly.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you @jjenzz!
0

You have to add the $http to your Controller. Like:

myApp.controller('MainController', function MainController($scope,$http) {...}

And with the usage of setIntervalthe code repeats again and again. In your case every second.

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.