javascriptsettimeoutcleartimeout

setTimeout never running, with or without clearTimeout


I have the following two functions:

window.onbeforeunload = null;
// this part is never executing
this.timeout = setTimeout(function(){
    console.log("redirecting");
    location.href="/dashboard";
}, 10000);
try { 
    // here I also call the other function
    await this.recorder.stop(); 
} 
catch (err) { 
    console.log(err); 
    clearTimeout(this.timeout);
}

And the second one that is called from this.recorder.stop();.

console.log("sending mail");
var self = this;
// console.log(blob instanceof Blob);
var file = new File([blob], "recording");
var formData = new FormData();
formData.append("recording", file);
formData.append("format", (this.isIOS ? "mp4" : "webm"));
formData.append("routine_id", this.routine_id);
axios.post('/room/send/recording', formData)
    .then(function (response) {
        if(response.data.result) {
            console.log("email has been sent")
        } else {
            console.log("failed to send email")
        }
    })
    .catch(({response}) => {
        console.log("an error occured during email call")
        console.error(response);
    })
    .finally(function() {
        clearTimeout(self.timeout);
        console.log("timeout cleared");
    });

But the redirect inside the setTimeout is never executing...
The console.log also does not run.

this.timeout = setTimeout(function(){
    console.log("redirecting");
    location.href="/dashboard";
}, 10000);

The console.log looks like this (no "redirecting" output)

sending mail
email has been sent
timeout cleared

Any clues as to why?


Solution

  • As pointed out by @SergeS , I had misunderstood how clearTimeout() works entirely. After clearTimeout, the function is not called anymore, therefore instead of

    clearTimeout(self.timeout);
    

    I also needed to call the function again. Since the function was only a single redirection something like this was fine

    clearTimeout(self.timeout);
    location.href="/dashboard";