I'm making an website game which uses many document.getElementById
inside a setInterval
that runs every 0.25 sec. This makes my webbsite slow after some time. I'm quite new to Javascript but I wonder if there's a more effective or efficient way to call and update a HTML element
or create a effective loop that includes game latency and runs every 1 sec?
Asked
Active
Viewed 76 times
2

Unamata Sanatarai
- 6,475
- 3
- 29
- 51

Turbotanten
- 25
- 3
-
2getElementById is the most efficient method to select an element there is, so if you're experiencing performace issues, the cause is more likely to be your own code than native implementations. – adeneo Apr 08 '14 at 12:37
-
providing us a piece of your code, would be more helpful so find a solution to your problem – n1kkou Apr 08 '14 at 12:38
-
http://stackoverflow.com/questions/7322078/jqueryid-val-vs-getelementbyidid-value – Govind Singh Apr 08 '14 at 12:39
-
JSPerf proves that `getElementById` is the faster than other methods http://jsperf.com/queryselectorall-vs-getelementbyid/6 – Fizer Khan Apr 08 '14 at 12:42
-
If you do proper DOM sanitation i.e. attach and remove event listeners you dont need, remove elements you dont need from the tree, i'm sure you will come close to a good performance. I would run the code and watch the DOM structure/JS objects closely to see where it is killing performance. – shanks Apr 08 '14 at 12:44
-
Why are you looking up the element every time? – epascarello Apr 08 '14 at 12:48
-
@epascarello -> cause he's new to javascript :) – Unamata Sanatarai Apr 08 '14 at 12:50
2 Answers
0
set variables outside (above) your setInterval function:
var myDiv = document.getElementById("ID");
and then call them inside the setInterval function:
myDiv.something()

Christopher Reid
- 4,318
- 3
- 35
- 74
0
Precache all ID
's.
Something in the lines of (pseudo code):
var all_objects = [];
...
onCreateObject = function(){
all_objects.push(newObject.id)
}
and then just iterate through the all_objects
variable.
As for the loop itself, there are solutions out there already: http://www.paulirish.com/2011/requestanimationframe-for-smart-animating/

Unamata Sanatarai
- 6,475
- 3
- 29
- 51
-
Whow prechace ID's sounds really promising! And thanks for the link to the loop solution. I will now google on how to precache my ID's. – Turbotanten Apr 08 '14 at 13:33