Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>You asked me for an example to improve the speed, I'm not an expert but here is what I would do:</p> <ol> <li><p>Don't use <code>setInterval</code> with string functions, they have to run through <code>eval</code> to run, so use this instead. In fact I wouldn't use <code>setInterval</code> at all for the main loop (see point #3).</p> <pre><code>setInterval(doSomething, 100) </code></pre></li> <li><p>Store an object you will be using multiple times (especially in a function that loops constantly). Even this example is not ideal:</p> <pre><code>var lisp = $('#lisp1'); function move() { var pos = parseInt( lisp.css("right"), 10 ); // always use a radix lisp.css("right", pos + 10 + "px"); } </code></pre></li> <li><p>For functions that loop constantly, be as short and concise as possible and eliminate extra function calls. From your second link, I compressed this code:</p> <pre><code>function move(){ $(".lisp").each(function(){ pos = parseInt($(this).css("right")); if (pos &gt; width) $(this).remove(); else $(this).css("right", pos+speed+"px") }); $(".bonus").each(function(){ pos = parseInt($(this).css("right")); if (pos &gt; width) $(this).remove(); else $(this).css("right", pos+speed+"px") }); $(".special").each(function(){ pos = parseInt($(this).css("right")); if (pos &gt; width) $(this).remove(); else $(this).css("right", pos+speed+"px") }); } </code></pre> <p>into this more concise version:</p> <pre><code>function move(){ $(".lisp, .bonus, .special").each(function(){ var pos = parseInt(this.style.right || 0, 10); if (pos &gt; width) { $(this).remove(); } else { this.style.right = pos + speed + "px"; } }); if (!over) { setTimeout(move, 10); } // use this instead of the setInterval() } </code></pre> <p>It's still not ideal, because your code keeps adding more and more objects. It should be limited because at one point I have over 200 objects on the screen and the page came to a crawl. This is also why I would use the <code>setTimeout</code> in the last line instead of the <code>setInterval</code> you use because the script may not have cycled through all of the elements before you want it to start again.</p></li> </ol> <p>I'm sure there are more points someone else could add to optimize my or your code even more :)</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload