Marco Tiberio
Marco Tiberio

Reputation: 5

How to stop a function after clicking 'OK' on confirm dialog box?

I have a javascript function involving blink detection, which affects a video. Basically, when you blink, a video embedded from Youtube stops playing and a confirm dialog box pops up allowing you to keep watching the video or reload the page. Once I click 'OK' the video should continue, but I would like the function to stop (or the camera to stop working), so to be able and watch the video till the end even if you blink.

I tried to play around with the function but I wasn't able to find my mistake.

Here you are the main code of the function:

function blink() {
    _blinked = true;
    _total += 1;

    const now = new Date();
    const timeDiff = (now - _start) / 1000; //in s
    // get seconds
    const seconds = Math.round(timeDiff);
    if(confirm(`You lasted ${seconds} seconds without blinking! Click OK to
    keep playing or CANCEL to watch full video!`)){}
    else    window.location.replace("fullvideo.html");
    _start = new Date();

    if (_timeOut > -1) {
        clearTimeout(_timeOut);
    }

    _timeOut = setTimeout(resetBlink, 500);
}

function resetBlink() {
    _blinked = false;
}

let _initialized = false;

Once I click 'OK' the video should continue, but I would like the function to stop (or the camera to stop working), so to be able and watch the video till the end even if you blink. Thank you very much.

Upvotes: 0

Views: 160

Answers (1)

KR34T1V
KR34T1V

Reputation: 493

The easiest way would be to have a global boolean which gets toggled by each function. We will call it status in this case:

var status = false;

function blink() {
    if (!status){
        status = true; // close function
        _blinked = true;
        _total += 1;

        const now = new Date();
        const timeDiff = (now - _start) / 1000; //in s
        // get seconds
        const seconds = Math.round(timeDiff);
        if(confirm(`You lasted ${seconds} seconds without blinking! Click OK to 
        keep playing or CANCEL to watch full video!`)){
        status = false; //open function to run again
        }
        else    window.location.replace("fullvideo.html");
        _start = new Date();

        if (_timeOut > -1) {
            clearTimeout(_timeOut);
        }

        _timeOut = setTimeout(resetBlink, 500);
    }
  }

Now your function will only run once, then if you click "OK" on the message it should be able to run once more.

Upvotes: 1

Related Questions