简体   繁体   中英

How can I fix my code to run only once in javascript

var timeToJoin = '18:13';
var today = new Date();
var time = today.getHours() + ":" + today.getMinutes();

var SST = 'https://meet.google.com/rnc-akmx-ubk';

if (time == timeToJoin) {
    joinClass();
}

function joinClass() {
    location.href = SST;
    setTimeout(offMicVideo, 10000);
}

function offMicVideo() {
    var video = document.getElementsByClassName('I5fjHe');
    var mic = document.getElementsByClassName('oTVIqe');

    for (var i = 0; i < video.length; i++) {
        video[i].click();
    }

    for (var i = 0; i < mic.length; i++) {
        mic[i].click();
    }
}

This is an extension which automatically joins meet at time But you have surely noticed a small problem in this if (time == timeToJoin) { condition whats happening here is when the correct time comes the extension tries to join the meeting but according to the if condition it tries to join the meeting every second till the if condition matches.

Please give me some solution to run the function inside the if statement only once .

This seems as simple as using another mechanism to ensure that the class is only joined once.

My recommendation would be to use a flag to indicate this, as so:

// Declare hasJoined outside of your looped code
var hasJoined = false;

// Inside your looped code
...
var SST = 'https://meet.google.com/rnc-akmx-ubk';

if (!hasJoined && time == timeToJoin) {
    hasJoined = true;
    joinClass();
}
...

The variable hasJoined must be declared outside of your loop code that monitors for the time. Otherwise you would overwrite the result each time the loop ran.

This works simply by checking that hasJoined is false before attempting to join the class. If hasJoined has not been set and it is time to join the class, hasJoined will be set and the joinClass() function will execute.

Changing hasJoined to true then prevents multiple attempts to join the class.

Try to put your if statement inside a time interval of 1 minute so it will check your condition only after 1 minute interval and will also reduce the unnecessary execution of code.

Considering the case that 1 minute late is allowed in the meeting:)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM