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.
setInterval and setInterval are effectively the same, window. setInterval is just more explicit.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With