AngularJS - Tweets & Add to array with delay

by gavinfoley

HTML

<div data-ng-app="myApp">
    <div data-ng-controller="MyCtrl">
        <ul class="ng-trans ng-trans-fade-right easeInOutBack" data-ng-repeat="tweet in tweets track by $index">
            <li>{{ tweet }}</li>
        </ul>
    </div>
</div>

CSS

</style> <!-- Ugly Hack due to jsFiddle issue: http://goo.gl/BUfGZ --> 
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/foundation/4.1.6/css/foundation.min.css"> 
<link rel="stylesheet" href="//rawgit.com/minipai/ng-trans.css/master/ng-trans.min.css"> 

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.20/angular.min.js"></script> 
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.20/angular-animate.min.js"></script> 
<script src="//cdnjs.cloudflare.com/ajax/libs/lodash.js/2.4.1/lodash.min.js"></script> 

<style>

JavaScript

angular.module('myApp', ['ngAnimate'])

.controller("MyCtrl", function($scope, $timeout, $http, Utils) {
    $scope.tweets = [];

    $http.get("http://dev.gavinfoley.ie/apis/twitter/api/twitter/angularjs")
        .then(function(response) {
            Utils.copyWithDelay(response.data.Tweets, $scope.tweets, 200);
        });
        
    Utils.wait(5).then(function(){
        Utils.pushWithDelay($scope.tweets, "Gav Test", 0);
    });

})

.factory("Utils", function($timeout) {

    var copyArrayWithDelay = function(sourceArray, destArray, milliDelay) {
        angular.forEach(sourceArray, function(item, i) {
            addItemToArrayWithDelay(destArray, item, i, milliDelay);
        });
    };

    var addItemToArrayWithDelay = function(destArray, item, counter, milliDelay) {
        var delay = parseInt(milliDelay, 10) || 300;
        $timeout(function() {
            return function() {
                destArray.push(item);
            };
        }(item), delay * counter);
    };

    var wait = function(seconds) {
        // return the $timeout's promise
        return $timeout(function() {
            // the return from this function is the value passed to the promise's success handler (the resolve value)
            return (seconds + ' seconds have elapsed');
        }, seconds * 1000);
    };

    return {
        copyWithDelay: copyArrayWithDelay,
        pushWithDelay: addItemToArrayWithDelay,
        wait: wait
    };

});