Is setInterval CPU intensive?

前端 未结 6 986
长情又很酷
长情又很酷 2020-11-29 04:14

I read somewhere that setInterval is CPU intensive. I created a script that uses setInterval and monitored the CPU usage but didn\'t notice a change. I want to know if there

6条回答
  •  春和景丽
    2020-11-29 04:43

    I don't think setInterval is inherently going to cause you significant performance problems. I suspect the reputation may come from an earlier era, when CPUs were less powerful.

    There are ways that you can improve the performance, however, and it's probably wise to do them:

    1. Pass a function to setInterval, rather than a string.
    2. Have as few intervals set as possible.
    3. Make the interval durations as long as possible.
    4. Have the code running each time as short and simple as possible.

    Don't optimise prematurely -- don't make life difficult for yourself when there isn't a problem.

    One thing, however, that you can do in your particular case is to use the onhashchange event, rather than timeouts, in browsers that support it.

提交回复
热议问题