thurmc thurmc - 1 year ago 123
Javascript Question

Call function after delay on page load using Angular

I am trying to call a function in Angular 2.5 seconds after a page loads to see if a form field has been autofilled. The function is being called but for some reason is only called if I navigate away from the field, change the tab, minimize the browser, etc. How can I accomplish this without requiring the user to do any of these actions (i.e. it is called 2.5 seconds after page load no matter what). I have two different implementations I have tried below but they behave the same way.

Method 1:

var timer=false;
$scope.$watch('email', function(){
timer= $timeout(function(){
}, 250)

Method 2:

<div class="form-managed" ng-init="load()"></div>

$scope.load = () => {
setTimeout(() => {
}, 2500);


From comments I changed the code to use $timeout instead of my other implementations. I also verified that the function is being called in any of the implementations however the value of the field still shows as null when I try to extract it. Current code below.

$timeout(() => {
var thisEmail = document.getElementById("buyerEmail");
}, 5000);

Input field:

<input type="email" class="form-control input-lg" name="email" id="buyerEmail" placeholder="Email address" autocomplete="email" ng-model-options="{updateOn: 'blur'}" ng-change="emailChanged($event)" required />

Answer Source

It doesn't make a difference how long the delay is that you add. If you populated the value of your email input from code, Angular doesn't see the change. This is why you only see the change reflected once you resize or make some other change that forces Angular to process the page.

While you didn't show it, I assume you have some code somewhere to assign the email value. Something like this, perhaps:


Change it to this:

$timeout(function () {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download