uksz
uksz

Reputation: 18699

How to define lambda function within a function?

I have an issue, where I cannot create lambda function within my function. I have the following:

start(){
        var idleTime = 0;
        var idleInterval = this.$interval(timerIncrement, 1000);

        $(document).on('mousemove keypress', function (e) {
            idleTime = 0;
        });

        function timerIncrement(){
                idleTime = idleTime + 1;
                if (idleTime > 2) {
                    this.$interval.cancel(idleInterval);
                    this.Service.logout();
                }
        }
}

I would like to function timerIncrement to have the same scope, so that it can cancel the interval when the idleTime is greater than some value. Right now, I cannot access $interval from within the function timerIncrement. Any ideas?

So far I've tried this:

      function timerIncrement(){
            return ()=> {
                idleTime = idleTime + 1;
                if (idleTime > 2) {
                    this.$interval.cancel(idleInterval);
                    this.Service.logout();
                }
            }
        }

However, the function inside return never gets called.

Upvotes: 2

Views: 114

Answers (2)

MartyIX
MartyIX

Reputation: 28646

For the sake of completeness, you can also make the following change:

var idleInterval = this.$interval(timerIncrement.bind(this), 1000);

I don't recommend it for your use case but sometimes it may come handy.

Upvotes: 0

uksz
uksz

Reputation: 18699

Alright, it wasn't that hard - I just had to define the function as variable.

        var timerIncrement:Function = () => {
            idleTime = idleTime + 1;
            if (idleTime > 2) {
                this.$interval.cancel(idleInterval);
                this.Service.logout();
            }
        };

And the scope is right.

Upvotes: 1

Related Questions