Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>There are several ways to handle something like this, here's just one off the top of my head.</p> <p>First of all, I see you're writing anonymous functions to put inside the setTimeout. I find it more elegant to bind a method of my object to its scope and send that to setTimeout. There's lots of ways to do hitching, but soon bind() will become standard (<a href="https://stackoverflow.com/questions/2025789/preserving-a-reference-to-this-in-javascript-prototype-functions/2025839#2025839">you can write this into your own support libraries yourself for browser compatibility</a>). Doing things this way would keep your variables in their own scope (no "that" variable in the global scope) and go a long way to avoiding bugs like this. For example:</p> <pre><code>function myObject(param){ // ... snip this.show = function(){ if(this.content.style.opacity &lt; 1){ this.content.style.opacity = (parseFloat(this.content.style.opacity) + 0.1).toFixed(1); setTimeout(this.show.bind(this),100); } } this.hide = function(){ if(this.content.style.opacity &gt; 0){ this.content.style.opacity = (parseFloat(this.content.style.opacity) - 0.1).toFixed(1); setTimeout(this.hide.bind(this),100); } } } </code></pre> <p>Second, you probably want to add some animation-handling methods to your object. setTimeout returns handles you can use to cancel the scheduled callback. If you implement something like this.registerTimeout() and this.cancelTimeout() that can help you make sure only one thing is going on at a time and insulate your code's behavior from frenetic user clicking like what you describe.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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