The Whiz of Oz
The Whiz of Oz

Reputation: 7043

SetInterval timer on multiple objects cancels after initializing

I have multiple objects displayed in my document that have states (statuses) on them. If an object's state is set to active, I display a count up timer to show users how long the object has been active for. Hence the code:

  countTimer = (el, seconds) ->
    setInterval (->
      totalSeconds = seconds
      ++totalSeconds
      hour    = Math.floor(totalSeconds / 3600)
      minute  = Math.floor((totalSeconds - (hour * 3600)) / 60)
      seconds = totalSeconds - (hour * 3600 + minute * 60)
      $(el).siblings('.status').find('.timer').text("#{hour}:#{minute}:#{seconds}")
    ), 1000

  $('.object').each (index, element) =>
    $el = $(element)
    secondsPassed = parseInt $el.data('start-time')
    if $el.data('state') == 'active'
      countTimer(element, secondsPassed)

On initialize, the script loads the correct time passed (based on data-start-time), e.g.

0:1:46

but then on the first second the timer of each element cancels out:

0:0:46

and then counts seconds only.

Not sure why that's happening. Any advice appreciated.

Fiddle: https://jsfiddle.net/fsob9qfb/

Upvotes: 0

Views: 43

Answers (1)

Murad Sofiyev
Murad Sofiyev

Reputation: 791

Try it without using variables Variables change as each call function

Upvotes: 1

Related Questions