xplat
xplat

Reputation: 8636

JavaScript timer is not working

I have created a file named ExtremeNotifications.js and added to the _Layout.cshtml master layout.

The ExtremeNotifications.js includes the following JavaScript code:

var extremeNotifications = extremeNotifications || {};

extremeNotifications = (function () {

    var baseURL = document.baseURI;
    var url = baseURL + 'api/usernotifications';
    var isNotificationServiceStarted = false;
    var timer;

    function getPendingNotifications() {
        $.ajax({ url: url, success: dataRetrieved, type: 'GET', dataType: 'json' });
    }

    function dataRetrieved(data) {
        alert(data);
    }

    function startNotifications() {
        if (!isNotificationServiceStarted) {
            timer = setInterval(getPendingNotifications, 3000);
            isNotificationServiceStarted = true;
        }
    }

    function stopNotifications() {
        clearInterval(timer);
        isNotificationServiceStarted = false;
    }

    return {
        start: startNotifications(),
        getPendingNotifications: getPendingNotifications(),
        isNotificationServiceStarted: isNotificationServiceStarted,
        stop: stopNotifications()
    }
})();

Then in my Home Index.cshtml I start the notifications with the following code and only if User.Identity.IsAuthenticated:

<script>
   extremeNotifications.start();
</script>

So now when my page starts and I'm authenticated user I get an alert box in the first time but I never see another alert after 3 seconds.

Any comments?

Upvotes: 1

Views: 37

Answers (1)

Pointy
Pointy

Reputation: 413826

You're close, but you're creating that returned object incorrectly:

return {
    start: startNotifications,
    getPendingNotifications: getPendingNotifications,
    isNotificationServiceStarted: isNotificationServiceStarted,
    stop: stopNotifications
};

By including the () after the function names, your code was calling the functions and returning their return values instead of returning references to the functions themselves.

Upvotes: 2

Related Questions