Silvia
Silvia

Reputation: 56

Prevent function from being called

so I have a function to measure the connection speed, and I have that running every 10 seconds (no need to click anywhere). In one of the conditions where speed is low, if it's true it calls other function that opens a pop-up with a message. My problem is that, the speed function is called every 10 sec, so every 10 sec (if the speed continues low) it calls the pop-up, and I don't want that.

I want to call the pop-up the first time the speed is low, and only again 1 min after if it's still low.

My code is this :

 if (speedMbps < low) {
                
                //call the function to open pop-up
                popup_speedtest();
            }

...

function popup_speedtest() {
//make the pop-up opens in vbhtml
$("#alert_speedtest").modal('toggle');
}

I thought about doing this

setTimeout(function() {
//make the pop-up opens in vbhtml
$("#alert_speedtest").modal('toggle');
}, 60000);

but that doesn't let the pop-up open the first time, and also, every time the function runs that setTimeout reset.

Any ideas?

Upvotes: 0

Views: 321

Answers (1)

David
David

Reputation: 218827

You'd want to track the state of having shown the modal. Add a variable for something like that:

let shownModal = false;

Then when you show the modal, check and/or update the variable and set your 1-minute timer to reset the variable. Something like this:

if (speedMbps < low) {
    if (!shownModal) {
        shownModal = true;
        popup_speedtest();
        setTimeout(function() {
            shownModal = false;
        }, 60000);
    }
}

That way it only performs the logic if the state is currently false and the logic is to set the state to true, show the modal, and set a timeout to return the state to false.

Upvotes: 1

Related Questions