2012-03-01 97 views
-4

有没有人知道为什么这不起作用?有条件的ClearTimeout不起作用

http://jsfiddle.net/jonevar/2Z2NQ/5/

这里是整个代码:

function ag_alert(message) { 

    event.preventDefault(); 

    //SetTimeout in case didn't close manualy 
    var timer = setTimeout(cls_message, 5000), 
     cur_url = window.location.href; 

    //Check if its already on 
    if (! $('.ag_alert_wrapper').is(':visible')) { 

     //Set the language 
     (cur_url.indexOf('/en/') >= 0) ? cls_txt = "close" : cls_txt = "閉じる" ; 

     $('<div class="ag_mess ag_alert_wrapper"></div><div class="ag_mess ag_alert_wrapper_close">'+ cls_txt +'</div>') 
      .prependTo('body'); 
     $('.ag_alert_wrapper') 
      .append('<p>'+ message +'</p>') 
      .animate({top : 0}, 200, function() { 
       $('.ag_alert_wrapper_close') 
       .animate({top : 90}, 200) 
       .on({ 
        mouseenter : function() { 
         $(this).animate({ 
          top : 100 
         }, 200); 
        }, 
        mouseleave : function() { 
         $(this).animate({ 
          top : 90 
         }, 200); 
        }, 
        click : function() { 
         cls_message(); 
        } 
       }); 
      }); 

     //Setups ESC key to close message 
     $(document).keydown(function(e) { 
      if (e.keyCode === 27) { 
       cls_message(); 
      } 
     }); 

    } else { 
     //if Alert is already visible 
     $('.ag_alert_wrapper') 
      .children('p').html(message) 
      .end() 
      .effect("highlight", { 
       color : '#FF0' 
      }, 1000); 

     clearTimeout(timer); 
    } 

} 


function cls_message() { 
    $('.ag_mess').animate({ 
     top : -200 
    }, 200, function() { 
     $('.ag_mess').remove(); 
    }); 
} 
+0

发生了什么? 'other_function'是否触发?数据的数据类型是否与条件类型匹配? – 2012-03-01 03:32:52

+0

怎么样是不工作?你的代码的其余部分在哪里? – j08691 2012-03-01 03:33:08

+0

我不知道问题是什么,但为什么即使设置超时,如果你要清除它在同一个函数的else分支?为什么不将'setTimeout()'移动到if分支中? – nnnnnn 2012-03-01 03:44:01

回答

1

这似乎是工作的罚款,测试代码(使用jQuery,但是这并不改变结论):

HTML

<div id="msgs"></div> 

js

function other_function() { 
    $('#msgs').append('other '); 
} 

function do_something(data) { 
    var timer = setTimeout(other_function, 500); 
    if (data === "condition") { 
     $('#msgs').append('hi '); 
    } else { 
     $('#msgs').append('clearing '); 
     clearTimeout(timer); 
    } 
} 

do_something('yay'); 

do_something('condition'); 

输出到DIV:

clearing hi other 

预期。活生生的例子:

希望这有助于。

+0

你会看看编辑过的文章。我只是添加了整个代码。 – Jay 2012-03-01 03:44:33

+0

从我看到的代码中没有'other_function' - 你可以制作一个显示你的问题的jsfiddle,否则你添加的代码有很多事情很难找出问题的出处。 – 2012-03-01 03:52:20

+0

这里是链接http://jsfiddle.net/jonevar/2Z2NQ/5/ – Jay 2012-03-01 04:00:06