Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

Ok so there is a couple things to this question.

First of 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.

like image 341
Jacob Avatar asked Aug 04 '11 16:08

Jacob


People also ask

What is the difference between setInterval () and window setInterval ()?

setInterval and setInterval are effectively the same, window. setInterval is just more explicit.

Which is better setTimeout or setInterval?

setTimeout allows us to run a function once after the interval of time. setInterval allows us to run a function repeatedly, starting after the interval of time, then repeating continuously at that interval.

How do I make setInterval faster?

Try doing: setInterval(function () { for (var i = 0; i < 1000; i++) { // YOUR CODE } }, 10); You will actually make your code more efficient by avoiding the callback calling overhead and having longer intervals will make your code run more predictably.

Is it good to use setInterval in JavaScript?

In order to understand why setInterval is evil we need to keep in mind a fact that javascript is essentially single threaded, meaning it will not perform more than one operation at a time.


2 Answers

  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.

like image 124
g.d.d.c Avatar answered Oct 08 '22 15:10

g.d.d.c


  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.

like image 32
kojiro Avatar answered Oct 08 '22 15:10

kojiro