Reputation: 3965
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:
Using window.
drawInterval = window.setInterval(draw, 60);
Not using window.
drawInterval = setInterval(draw, 60);
Part B:
Not using quotes and brackets around the function name
drawInterval = setInterval(draw, 60);
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.
Upvotes: 20
Views: 11441
Reputation: 339836
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.
Upvotes: 0
Reputation: 77137
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.
If you use quotes, the setInterval() essentially "evals" the statement. That's bad. Don't use the quotes.
Upvotes: 5
Reputation: 11238
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.
Upvotes: 3
Reputation: 47988
Unless you've declared your own locally scoped setInterval
function, there's no difference between setInterval
and window.setInterval
.
The second form uses an implied eval()
. This should be avoided when possible because it presents the potential for code injection.
Upvotes: 25
Reputation: 78530
As for prefixing it with window.
, there's not a lick of difference. You can use either.
Upvotes: 2
Reputation: 136114
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.
Upvotes: 4
Reputation: 22054
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
Upvotes: 1