Stopping setInterval in coffeescript

左心房为你撑大大i 提交于 2019-12-25 00:52:25

问题


How can I stop the setInterval in my script ? Alert working, clearInterval not, and there isn't any error in console.

order =  
  start_poll: ->
    interval = setInterval(@request, 60000)
  stop_polling: ->
    clearInterval order.start_poll()
    alert ('expired')
  request: ->
    id = $('#status_id').attr('data-id')
    $.get "/orders/#{id}", (data) ->
      console.log("#{data.status}")
      if data.status is 'expired'
        order.stop_polling()


$ ->
  order.start_poll()

回答1:


setInterval returns a new timer ID every time you call it and you pass that ID clearInterval to stop that specific timer. So when you do this:

clearInterval order.start_poll()

you're just starting a new timer and immediately stopping it, this won't have any affect whatsoever on other timers.

You need to store the ID so that you can cancel it later:

order =  
  start_poll: ->
    @interval = setInterval(@request, 60000)
  stop_polling: ->
    clearInterval(@interval) if(@interval)
    alert('expired')
  #...

You might want to add a @stop_polling() call to the top of start_poll too. This isn't necessary but it can't hurt and it will help prevent future bugs if you decide to change how you interact with the polling.



来源:https://stackoverflow.com/questions/26872015/stopping-setinterval-in-coffeescript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!