简体   繁体   中英

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 ), eg

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/

在不使用变量的情况下进行尝试变量随每个调用函数而变化

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM