How can I execute javascript code every a specific time interval?

后端 未结 1 1436
Happy的楠姐
Happy的楠姐 2020-12-12 06:59

I want to ping the server every 2 minutes using jQuery. I thought about an open loop with setTimeout function but I think this would crush the browser - any suggestions ?

1条回答
  •  [愿得一人]
    2020-12-12 07:32

    Do not use setTimeout() for this type of action, rather use setInterval().

    var intervalId = setInterval(function() {
        /* Do your magic */
    }, 2000);
    

    To clear your interval, simply clearInterval(intervalId), when you wish to stop the ping:ing.

    0 讨论(0)
提交回复
热议问题