2

I have a jQuery function that creates an element when the user hovers on a element. When the mouse goes away from the element I set a timeout to destroy it. While creating and normally destroying the element does work flawlessly, the remove inside the timeout does not work and dies silently. I suspect there is some problem in the interaction between window.setTimeout and jQuery.remove, but couldn't find anything on the web.

My code:

//Element creation
function createElement(){
    $(".my_class").remove()
    content = compose_content() //It's an <ul>
    $('<div></div>', {
        class : "my_class",
        html: content
     }).insertAfter($("#first_row"))
}

//Element destruction
function setDestroyTimeout(){
    if(perform_some_checks()){
         window.setTimeout(function(){
              console.log("Removing...")
              $(".my_class").remove()
         }, 1000)
    }
}

$(".another_class").hover(createElement(), setDestroyTimeout())

The first remove (the one in the createElement function) works smoothly, while the second doesn't do anything. The Timeout works as well, I checked with the console.log instruction.

frollo
  • 1,296
  • 1
  • 13
  • 29
  • 1
    Call vs reference `$(".another_class").hover(createElement(), setDestroyTimeout())` ==> `$(".another_class").hover(createElement, setDestroyTimeout)` – Tushar Mar 17 '16 at 13:20
  • Could you please expand it? It's somewhat unclear – frollo Mar 17 '16 at 13:22
  • 1
    The `()` in `setDestroyTimeout()` calls the function `setDestroyTimeout`. The result of that function call (in your case `undefined`) is then passed as callback to your `hover`. Look at this related question: [Why is the method executed immediately when I use setTimeout?](http://stackoverflow.com/questions/7137401) – t.niese Mar 17 '16 at 13:25
  • The element is probably not created yet when you set the second destroy, the jquery try to remove, but the element is not add yet. – Luan Soares Mar 17 '16 at 13:26
  • The problem was the one @t.niese (and I also suspect @Tushar) pointed out. Thanks! – frollo Mar 17 '16 at 13:30

0 Answers0