问题
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