stop function that run with setTimeout

前端 未结 3 1433
梦如初夏
梦如初夏 2020-12-07 04:15

I want stop my function that run with setTimeout and do not show image followed mouse. I want do that with button click, how do that? my code:



        
相关标签:
3条回答
  • 2020-12-07 05:06
    var foobarTimeout = setTimeout(foobar, 1000);
    
    ...
    
    clearTimeout(foobarTimeout);
    

    See:
    https://developer.mozilla.org/en/DOM/window.setTimeout
    https://developer.mozilla.org/en/DOM/window.clearTimeout

    0 讨论(0)
  • 2020-12-07 05:10

    Save the return value of setTimeout, which is a "handle" for the timer, and when you want to cancel it, call clearTimeout with that value.

    So in your code, you'd declare a timerHandle variable somewhere appropriate, then set it here:

    if (displayduration > 0)
        timerHandle = setTimeout("hidetrail()", displayduration * 1000);
    

    ...and then create a button click handler:

    function cancelTimeoutOnClick() {
        if (timerHandle) {
            clearTimeout(timerHandle);
            timerHandle = 0;
        }
    }
    

    Off-topic: It's almost never best practice to pass strings into setTimeout, that's an implicit eval. In your case, just pass the function reference:

    if (displayduration > 0)
        timerHandle = setTimeout(hidetrail, displayduration * 1000);
                              // ^--- Difference here (no quotes, no parentheses)
    
    0 讨论(0)
  • 2020-12-07 05:10

    you use timeout like >

    var myTimeout = setTimeout(yourfunction);
    

    and then you can cancel it >

    clearTimeout(myTimeout);
    
    0 讨论(0)
提交回复
热议问题