Skip to content

Instantly share code, notes, and snippets.

@dassiorleando
Last active March 24, 2018 08:11
Show Gist options
  • Save dassiorleando/670b98a2e3b422e8692e304cacfa0443 to your computer and use it in GitHub Desktop.
Save dassiorleando/670b98a2e3b422e8692e304cacfa0443 to your computer and use it in GitHub Desktop.
Using $timeout and setTimout in AngularJs App
/**
* Simple script to show how to solve the scrope update
* When using the native js TimeOut call
*
* @author dassiorleando
*/
(function (angular) {
'use strict';
angular
.module('myApp', []) // Define our angular app
.controller('IndexController', IndexController); // We setup the controller
IndexController.$inject = ['$scope', '$timeout'];
function IndexController($scope, $timeout) {
$scope.firstMessage = 'First message';
$scope.secondMessage = 'Second message';
// Let's update the first message after 2 seconds
// Angular $timeout service
$timeout(function() {
$scope.firstMessage = 'First message updated';
alert($scope.firstMessage);
}, 2000);
// Let's update the second message after 2 seconds
// Native implementation
setTimeout(function() {
$scope.secondMessage = 'Second message updated';
alert($scope.secondMessage);
}, 2000);
// Be aware that if the $timeout was called at the second place the digest could be also updated
// That means both messages will be updated despite the use of setTimeout.
}
})(window.angular);
@thewindcolince
Copy link

thanks for sharing

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment