Is there a way to ensure my JavaScript code runs only once?

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

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

if (currentTime == startTime) {
    joinMeeting();
}

function joinMeeting() {
    location.href = meetLink;
    setTimeout(turnOffMicVideo, 10000);
}

function turnOffMicVideo() {
    var videoElements = document.getElementsByClassName('I5fjHe');
    var micElements = document.getElementsByClassName('oTVIqe');

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

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

An automated extension to join a Google Meet session at a specific time. However, there is an issue with the repeated execution of the function inside the if statement every second until it matches the condition. Any suggestions on how to ensure the function runs only once?

Answer №1

To ensure that the class is only joined once, it can be as simple as implementing a different mechanism.

One suggestion would be to use a flag as shown below:

// 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();
}
...

It's important to declare the variable hasJoined outside of the looping code that checks for the joining time. Otherwise, the result would be overwritten each time the loop runs.

This method simply requires verifying that hasJoined is set to false before attempting to join the class. If hasJoined hasn't been activated and it's time to join the class, hasJoined will be triggered, leading to the execution of the joinClass() function.

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

Answer №2

For optimal performance, consider placing your if statement within a timer set for a 1-minute interval. This will ensure that your condition is checked only after each minute, minimizing unnecessary code execution.

Remember the golden rule: Being 1 minute late to a meeting is perfectly acceptable :)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tricks for preventing axios from caching in GET requests

I am utilizing axios in my React-Native application Firstly, I set up the headers function setupHeaders() { // After testing all three lines below, none of them worked axios.defaults.headers.common["Pragma"] = "no-cache"; axios.defaults.heade ...

Incorporating User Input: Adding Paragraph Elements with HTML and Javascript to a Div Container

I am attempting to test my ability by creating a basic webpage. My goal is to take the text entered by the user in a textarea and add it to the page using a button. This button should generate a new paragraph element, place the user input inside of it, and ...

Transferring data from an Express server to a React frontend perspective

I am relatively new to working with the MERN stack, so please forgive me if this question sounds novice. I am currently developing an application that is designed to visit a specific URL, extract some text data from it, and then display this information on ...

Exploring the contrast between positive and negative numbers in javascript

I am facing a unique challenge with my Javascript function that counts the number of sorted numbers in an array. Strangely, it seems to work perfectly fine for positive numbers, but when negative numbers are involved, the function treats them as if they ...

Iterate through the xml.documentElement in a loop

I want to show 8 men and 2 women in SVG format. However, my current function only displays one man and woman. How can I add a loop to make this work for all individuals? for (i = 0; i < Serie[n].Number; i++) { return xml.documentElement } The data arr ...

Is there a way to delete objects that are added dynamically to an array using a specific button linked to each object?

I am currently using Angular to develop a shopping list application. To facilitate testing, I have set up two pre-made lists with two and three pre-defined items each. However, the goal is for users to dynamically add both items and lists themselves in the ...

Searching within a container using jQuery's `find` method can sometimes cause jQuery to lose control

I am trying to extract information from an input field within a table in a specific row. Here is the code I am using: var myElements = $('#myTable tbody').find('tr'); console.log(myElements); This correctly displays the items in the ...

What is the purpose of using Array.prototype.slice.call(nodeList) for handling DOM elements?

Many JavaScript libraries like jQuery and Zepto frequently use Array.prototype.slice.call on querySelectorAll(), getElementsByTag, or ClassName results. Despite browsing numerous questions and answers on StackOverflow about this topic, I understand that it ...

How can I modify certain attributes within an array of objects?

https://i.sstatic.net/TKkcV.jpgI need help with updating properties within an object array. Below is my code for reference. I have an object array consisting of two arrays, where the first one contains attribute "first" and the second one contains "last". ...

What benefits and drawbacks come with setting up JS libraries in resource files compared to package.json?

Configurations for JavaScript libraries such as Babel, Nyc, Eslint, and many others can be specified in resource files or within the package.json. For example, Babel can be set up in a .babelrc file or through a babel entry in the package.json. What are ...

Attempting to grasp the concept of implementing an If statement in conjunction with an event

Check out this HTML code snippet <body> <div> <button> Button A </button> <button> Button B </button> <button> Button C </button> </div> </body> This is my att ...

streaming an HTML5 video directly from memory source

After retrieving multiple encrypted data using ajax queries and performing necessary manipulations to turn them into a valid video, I find myself at a standstill. The binary of the video is now stored in memory, but I am unsure how to display it. To confi ...

Obtaining a list of dates for a particular week using React DayPicker

I'm seeking the ability to click on a specific week number within the react DayPicker and receive an array of all dates within that week. The DayPicker package I am using can be found here: I've copied the example code from react DayPicker to e ...

Managing link clicks using jQuery

I have a question that seems simple, but I am struggling to find the correct solution. In my phonegap app, I have a login feature where I check the results using ajax after the user clicks: <a href="home.html" data-transition="pop">GO</a> The ...

When crafting an XPATH expression, I am able to navigate within the #document element. Within this element, I must specify the path to the HTML body of my web page

I need assistance with my HTML page, can someone please help? Here is the XPath code I am using: (//span[text()='Information']//following::div[contains(@class,'edit-area')])[1]/iframe However, when I run my script, it says that there ...

Issue with resizing browser window when using three.js EffectComposer

My current rendering setup encounters a resizing issue when adjusting the browser window size. In my setup, I am rendering two scenes - one for objects with postprocessing effects applied. The postprocessing effects are achieved using THREE.EffectComposer ...

Automatically disconnect from the application upon logging out of Google account

I've successfully set up an express server that uses Google OAuth for user authentication. One interesting challenge I'm facing is how to handle the scenario where a user logs out of Google services (like Gmail) and automatically log them out fro ...

Activate the camera movement using DeviceOrientationControls

Currently, I am working on a webVR application using Three.js. I have successfully integrated DeviceOrientationControls, but now I am looking for a way to navigate the virtual environment using the magnet button on the google cardboard. My goal is to have ...

Rendering data in React using the array indexRendering data in React

I'm encountering an issue in React JS where I need to display all data from a REST API with a numeric index. REST API: [ { "id": "1", "start_date": "2020-05-08 09:45:00", "end_date": "2020-05-08 10:00:00", "full_name": "mirza", "cust_full_name": "fu ...

Pass the extended object from the service to the controller within a promise using the .map function

section: I am currently working on extending a JSON object within a service and passing it to a controller. The JSON originally came to the service from another service that makes backend calls. The code is quite intricate, so I've added comments an ...