0

What's wrong with the code, I am unable to stop setInterval.

Error: changedHandler_BB is undefined.

...

var changedHandler_BB = setInterval(function() {

    $("#wc_room_container_BB").addClass('active_chat_block_blink_effect');

    setTimeout(function() {
        $("#wc_room_container_BB").removeClass('active_chat_block_blink_effect');
    }, 500);

}, 1000);

...

$("#wc_block_BB").click(function(){

    var newID = $("#LatestLastID_BB").val();

    $("#worldchat_last_id_BB").val(newID);

    clearInterval(changedHandler_BB);
});
Andreas Louv
  • 46,145
  • 13
  • 104
  • 123
webfreaks
  • 55
  • 1
  • 7

3 Answers3

0

Just remove 'var':

changedHandler_BB = setInterval(function() {...}); //setting variable on global scope {window.changedHandler_BB }
A. Wolff
  • 74,033
  • 9
  • 94
  • 155
  • thanks for reply, Now error has removed now but still clearInterval is not working – webfreaks May 21 '13 at 12:10
  • Yes, downvoting because that is dangerous advice. There are plenty of ways to create the variable in the correct scope without carelessly tossing it into the global scope. If nothing else, assign it directly to the `window` object, but don't just drop the `var` declaration. – Derek Henderson May 21 '13 at 12:13
  • I'm not the down-voter but remember, [Global variables are evil](http://yuiblog.com/blog/2006/06/01/global-domination/). – Beetroot-Beetroot May 21 '13 at 12:14
  • @Derek Henderson Judging by customized name of variable, i don't think it could be a problem here, anyway, you are correct, better is to use closure. – A. Wolff May 21 '13 at 12:18
0

As per the comment's above - you defined changedHandler_BB inside a function. You need to define that in outer scope so that it become accessible in another functions

try this -

var changedHandler_BB;

function someFunction() {
    changedHandler_BB = setInterval(function () {
        $("#wc_room_container_BB").addClass('active_chat_block_blink_effect');
        setTimeout(function () {
           $("#wc_room_container_BB").removeClass('active_chat_block_blink_effect');
        }, 500);
    }, 1000);
}
$("#wc_block_BB").click(function () {
    var newID = $("#LatestLastID_BB").val();
    $("#worldchat_last_id_BB").val(newID);
    clearInterval(changedHandler_BB);
});
Adil Shaikh
  • 44,509
  • 17
  • 89
  • 111
0

changedHandler_BB is in another function. Thus, it is in that function's scope and not in scope accessible by clearInterval inside your click event handler. This is why it is undefined when you attempt to access it.

You need to make sure that either changedHandler_BB is in the same scope as your click event listener or can be otherwise accessed by it.

Derek Henderson
  • 9,388
  • 4
  • 42
  • 71