开发者

Which way is better, setInterval() or window.setInterval()?

开发者 https://www.devze.com 2023-03-26 10:36 出处:网络
Ok so there is a couple things to this question. First o开发者_运维知识库f all, i\'m asking this for setTimeout() and for setInterval()

Ok so there is a couple things to this question.

First o开发者_运维知识库f all, i'm asking this for setTimeout() and for setInterval()

I have seen a couple different ways to call them and i'm wondering which way is the best for this circumstance..

I'm making a js/canvas game and I'm just looking over my draw interval (where it loops the draw method)

Anyways, here are the different ways I have seen...

Part A:

  1. Using window.

    drawInterval = window.setInterval(draw, 60);
    
  2. Not using window.

    drawInterval = setInterval(draw, 60);
    

Part B:

  1. Not using quotes and brackets around the function name

    drawInterval = setInterval(draw, 60);
    
  2. Using quotes and brackets around the function name

    drawInterval = setInterval("draw()", 60);
    

So for Part A: should i use window. or not? And what about window.clearInterval() vs clearInterval by itself?

And for Part B: should I use quotes and brackets or not? I was told before that it was a bad idea to use quotes and brackets for this situation.


  1. Unless you've declared your own locally scoped setInterval function, there's no difference between setInterval and window.setInterval.

  2. The second form uses an implied eval(). This should be avoided when possible because it presents the potential for code injection.


  1. window is the global object. Whether or not you use it explicitly is something of a matter of style, but as a Python developer, I think explicit is better.

  2. If you use quotes, the setInterval() essentially "evals" the statement. That's bad. Don't use the quotes.


window.setInterval() and setInterval() are exactly the same - the window part is implicit and can be omitted.

both setTimeout and setInterval will eval a string, but best practice is to sent a reference to the function - therefore no quotes.


The calls in part A are the same (unless you redeclare one of those functions somewhere). It comes down to preference- I prefer to leave off window as it's unnecessary.

For part B, option 1 is definitely the better practice. Option 2 is going to eval that string, and eval should almost always be avoided.


As for prefixing it with window., there's not a lick of difference. You can use either.


Not sure on the window.setInterval vs just setInterval

But, it's better to always pass a function, rather than string to setInterval and setTimeout


Another good reason to use window.setTimeout instead of just setTimeout is that it allows you to give just a single declaration to jshint of which global objects your code depends on:

/*global window */

thus allowing access to all of the window methods without having to specify each of them individually in your jshint directives.

0

精彩评论

暂无评论...
验证码 换一张
取 消