Home » Javascript » To closure or not to closure

To closure or not to closure

Posted by: admin November 1, 2017 Leave a comment

Questions:

I am trying to create a function that two things:

(1) It should check if a div element is showing up on a page

(2) Whenever the element shows up, I need to show a live timer on the page that shows how long the element has been visible on the page.

The issue is I have a global variable called timer (initialized to 0). As a result, when I am viewing the element for the first time, the timer works as supposed to (timer += end time – start time).

However when I scroll away from the element, the timer is re-set to the initial value of 0. So on the second time around, the timer restarts at 0. However on the second time, I want the timer to start from where it was the last time.

I tried doing this with closure but cannot.

Can anyone help? My pseudo code is as follows:

     var timer = 0, t1 = 0;
     function counter() {
         (function func() {
             //check is item is visible
             //if visible, then t1 = Date.now()
             //if item not visible, then t1 = 0
         })()
         //calculate time elapsed based on t1 above
         return timer;
     }
Answers: