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()
setInterval
returns a new timer ID every time you call it and you pass that IDclearInterval
to stop that specific timer. So when you do this: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:
You might want to add a
@stop_polling()
call to the top ofstart_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.