Answers for "settimeout cleartimeout not working"

16

js cleartimeout

var myVar;

function myFunction() {
  myVar = setTimeout(function(){ alert("Hello"); }, 3000);
}

function myStopFunction() {
  clearTimeout(myVar);
}
Posted by: Guest on February-19-2020
0

cleartimeout() clears the time out that has been previously set by

I had trouble finding a good source, so I tried running this script in my browser.

var doItLater = function () {
    alert("I did it!");
};

window.onload = function () {
    // set a timeout to execute immediately
    var timeout = window.setTimeout(doItLater, 0);

    for (var i = 0; i < 1000000000; i++) {
        // waste some time
    }
    // The timeout has definitely triggered by now.
    // doItLater is queued up to execute as soon as
    // this function returns.

    clearTimeout(timeout); // wait, I changed my mind!
};

// Does doItLater get called?
And it works! clearTimeout() prevents doItLater() from being called, even though it's been placed on the queue already.

On a side note, I would definitely recommend using setTimeout() within your render function to prevent the page from becoming unresponsive. 1000 ms is way too long for a function to block the event loop. (for example, see here)
Posted by: Guest on March-17-2021

Code answers related to "settimeout cleartimeout not working"

Code answers related to "Javascript"

Browse Popular Code Answers by Language