Stop setInterval call in JavaScript

前端 未结 16 1853
星月不相逢
星月不相逢 2020-11-21 05:00

I am using setInterval(fname, 10000); to call a function every 10 seconds in JavaScript. Is it possible to stop calling it on some event?

I want the us

16条回答
  •  终归单人心
    2020-11-21 05:36

    The answers above have already explained how setInterval returns a handle, and how this handle is used to cancel the Interval timer.

    Some architectural considerations:

    Please do not use "scope-less" variables. The safest way is to use the attribute of a DOM object. The easiest place would be "document". If the refresher is started by a start/stop button, you can use the button itself:

    Start
    
    
    

    Since the function is defined inside the button click handler, you don't have to define it again. The timer can be resumed if the button is clicked on again.

提交回复
热议问题