0

I have a user control that has a timer in it. The timer is being updated every 5 seconds using javascript within the user control itself. During run time, a few instances of my user control is created. I place them inside an update panel. The timer works just fine when there is only one instance of my user control. But when there is more than one instance, only the last instance gets updated every 5 seconds. The earlier instances don't get updated.

Here's my javascript:

var start = new Date('<%=session.startTime%>');
var stat = '<%=session.status%>'

UpdateValues();
AutoUpdateValues();

function AutoUpdateValues(){
    setInterval(function () {
        UpdateValues();
    }, 5000);
}

function UpdateValues() {
    //update time elapsed
    var totalSec = Math.ceil((new Date() - start) / 1000); //time elapsed in seconds
    var hr = Math.floor(totalSec/3600);
    var min = Math.floor((totalSec % 3600)/60);
    var sec = totalSec % 60;
    if (stat == 2) {
        $('#<%=lblTimeElapsed.ClientID%>').text(hr + "h " + min + "m " + sec + "s" );
    }
}

I read about the use of passing the context to my method here but I don't know how to implement this in my code. Any help, please? Thanks

Community
  • 1
  • 1
Rian
  • 171
  • 16
  • you can only have one ID per dom, but you might be able to cheat by using `$('[id=<%=lblTimeElapsed.ClientID%>]')` – dandavis Apr 12 '15 at 03:50
  • Any reason why you can't use classes instead of ID? As @dandavis says, can only have one ID per DOM but can have multiple instances of a class. $().text would apply to all instances. – concrete_d Apr 12 '15 at 07:18
  • @concrete_d each instance of the user control has its own values. If I used class then the script from one instance of the user control will affect the controls in other instances of the user control since they would have the same class and they are instantiated at the same time in the same page. Isn't that what's gonna happen? – Rian Apr 12 '15 at 08:28
  • @dandavis Hi. Thanks for your suggestion. Tried it but got the same result. Only the last instance gets updated. – Rian Apr 12 '15 at 08:35
  • Do you mean clicking on one user control would affect the other? It's possible to set a class on multiple DOM elements and only have click events affect the actual element that gets clicked (i.e. using 'this' value in jQuery). There's an example on this page: https://api.jquery.com/click/ – concrete_d Apr 12 '15 at 08:41

1 Answers1

0

it maybe that:

var start = new Date('<%=session.startTime%>');
var stat = '<%=session.status%>'

are getting overritten in each run because they are public, so start and stat contain the last instance value, i had a simmilar problem and solved it by putting my variables inside the setInterval function or in your case inside the UpdateValues function

Esset
  • 916
  • 2
  • 15
  • 17