Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call a function periodically on server in background in angularjs

I have an API on q server that looks like this:

function isLoggedIn(){
   ....
    }

This API tell whether a user is logged in or not.

I want to call this API every 15 minutes or within any interval, to check whether the user is authenticated or not on my angular app.

My concern is how to call an API in intervals, and where to write this method.

like image 368
Naushad Ahmad Avatar asked Dec 25 '22 13:12

Naushad Ahmad


1 Answers

Use setInterval in your main controller.

setInterval(function(){ 
    // call your service method here
    //isLoggedIn(); in your case
 }, 3000); // This is time period in milliseconds 1000 ms = 1 second.

Or

use $interval service is injected into your controller function, you can use it to schedule repeated function calls. Here is an example that used the $interval service to schedule a function call every 5 seconds:

var myapp = angular.module("myapp", []);

myapp.controller("MyController", function($scope, $interval){

    $interval(isLoggedIn, 5000);

});

function isLoggedIn() {
    console.log("Interval occurred");
    // call your service method here
}
like image 76
Kashif Mustafa Avatar answered Dec 28 '22 06:12

Kashif Mustafa