stop settimeout in recursive function

后端 未结 7 2103
旧时难觅i
旧时难觅i 2020-12-01 11:24

my problem is that I can not stop a timer.

I had this method to set a timeout from this forum. It supposed to store the identifyer in the global variable. By accid

7条回答
  •  北海茫月
    2020-12-01 11:59

    I think that most people are getting at the reason why this isn't working, but I thought I would provide you with updated code. It is pretty much the same as yours, except that it assigns the timeout to a variable so that it can be cleared.

    Also, the anonymous function in a setTimeout is great, if you want to run logic inline, change the value of 'this' inside the function, or pass parameters into a function. If you just want to call a function, it is sufficient to pass the name of the function as the first parameter.

    var timer = null; 
    
    var updatetimer = function () {
        //do stuff
    
        // By the way, can just pass in the function name instead of an anonymous
        // function unless if you want to pass parameters or change the value of 'this'
        timer = setTimeout(updatetimer, 10000);
    };
    
    //this should start and stop the timer
    $("#mybutton").click(function(e) { 
         e.preventDefault();
         if($('#mydiv').is(':visible')){
            $('#mydiv').fadeOut('normal');
            clearTimeout(timer);  // Since the timeout is assigned to a variable, we can successfully clear it now
    
        } else{
            $('#mydiv').fadeIn('normal');
            updatetimer();
       }
    });
    

提交回复
热议问题