Use your computer as a server for js [closed]

I have a website and I simply want a way to creat an account and sign in, with username and password in js, that’s the easy part, I don’t know how to host a server, is there a free way? I simply need somewhere to store the username and password pair, it does not have to be encrypted or anything but it would be a nice bonus. Is there a way to do this for free? The amount of data won’t really be that much. And what language would up I use to get data from it, could I use js? Any help would be greatly appreciated:)

Firebase VideoChat Error (Invalid document reference. Document references must have an even number of segments, but calls has 1.)

I am trying to make a web-chat SPA web application using WebRTC, Firebase and React.js . Currently the collection in the database is being created under calls, but inside the document it just says NEW and there is no callId etc to allow me to connect the two users. Have been stuck on this for some time now.. Does anyone see the issue here? The error I am getting is “Uncaught FirebaseError: Invalid document reference. Document references must have an even number of segments, but calls has 1.”

import React, { useState, useRef, useEffect } from 'react';
import { doc, collection, setDoc, updateDoc, getDoc, onSnapshot, addDoc } from 'firebase/firestore';
import { getFirestore } from 'firebase/firestore';
import { getAuth } from 'firebase/auth';

const db = getFirestore();
const auth = getAuth();

const VideoCall = () => {
  const [localStream, setLocalStream] = useState(null);
  const [remoteStream, setRemoteStream] = useState(null);
  const [callId, setCallId] = useState('');
  const [isCaller, setIsCaller] = useState(false);
  const [iceCandidatesQueue, setIceCandidatesQueue] = useState([]);

  const peerConnectionRef = useRef(null);
  const webcamButtonRef = useRef(null);
  const callButtonRef = useRef(null);
  const answerButtonRef = useRef(null);
  const callInputRef = useRef(null);
  const webcamVideoRef = useRef(null);
  const remoteVideoRef = useRef(null);

  const initializePeerConnection = () => {
    if (peerConnectionRef.current) return;

    peerConnectionRef.current = new RTCPeerConnection({
      iceServers: [{ urls: 'stun:stun.l.google.com:19302' }],
    });

    peerConnectionRef.current.onicecandidate = (event) => {
      if (event.candidate) {
        const candidatesCollection = isCaller
          ? collection(doc(db, 'calls', callId), 'offerCandidates')
          : collection(doc(db, 'calls', callId), 'answerCandidates');

        addDoc(candidatesCollection, event.candidate.toJSON());
      }
    };

    peerConnectionRef.current.ontrack = (event) => {
      const [remoteStream] = event.streams;
      if (remoteStream) {
        setRemoteStream(remoteStream);
      }
    };
  };

  useEffect(() => {
    if (peerConnectionRef.current && peerConnectionRef.current.remoteDescription) {
      iceCandidatesQueue.forEach(candidate => {
        peerConnectionRef.current.addIceCandidate(candidate);
      });
      setIceCandidatesQueue([]); // Clear the queue after adding
    }
  }, [peerConnectionRef.current?.remoteDescription]);

  const handleWebcamButtonClick = async () => {
    const stream = await navigator.mediaDevices.getUserMedia({ video: true, audio: true });
    setLocalStream(stream);

    if (peerConnectionRef.current) {
      stream.getTracks().forEach(track => peerConnectionRef.current.addTrack(track, stream));
    }

    webcamVideoRef.current.srcObject = stream;
  };

  const handleCallButtonClick = async () => {
    initializePeerConnection();

    // Create a new document for the call
    const callDocRef = doc(collection(db, 'calls')); // Create a new document reference in 'calls'
    const offerCandidatesRef = collection(callDocRef, 'offerCandidates');
    const answerCandidatesRef = collection(callDocRef, 'answerCandidates');

    setCallId(callDocRef.id);
    setIsCaller(true);

    // Create offer
    const offerDescription = await peerConnectionRef.current.createOffer();
    await peerConnectionRef.current.setLocalDescription(offerDescription);

    await setDoc(callDocRef, { offer: { sdp: offerDescription.sdp, type: offerDescription.type } });

    onSnapshot(callDocRef, snapshot => {
      const data = snapshot.data();
      if (data?.answer && !peerConnectionRef.current.remoteDescription) {
        const answerDescription = new RTCSessionDescription(data.answer);
        peerConnectionRef.current.setRemoteDescription(answerDescription);
      }
    });

    onSnapshot(answerCandidatesRef, snapshot => {
      snapshot.docChanges().forEach(change => {
        if (change.type === 'added') {
          const candidate = new RTCIceCandidate(change.doc.data());
          if (peerConnectionRef.current.remoteDescription) {
            peerConnectionRef.current.addIceCandidate(candidate);
          } else {
            setIceCandidatesQueue(queue => [...queue, candidate]);
          }
        }
      });
    });
  };

  const handleAnswerButtonClick = async () => {
    initializePeerConnection();

    const callDocRef = doc(db, 'calls', callId);
    const answerCandidatesRef = collection(callDocRef, 'answerCandidates');
    const offerCandidatesRef = collection(callDocRef, 'offerCandidates');

    setIsCaller(false);

    const callData = (await getDoc(callDocRef)).data();
    const offerDescription = callData.offer;

    await peerConnectionRef.current.setRemoteDescription(new RTCSessionDescription(offerDescription));

    const answerDescription = await peerConnectionRef.current.createAnswer();
    await peerConnectionRef.current.setLocalDescription(answerDescription);

    await updateDoc(callDocRef, { answer: { sdp: answerDescription.sdp, type: answerDescription.type } });

    onSnapshot(offerCandidatesRef, snapshot => {
      snapshot.docChanges().forEach(change => {
        if (change.type === 'added') {
          const candidate = new RTCIceCandidate(change.doc.data());
          if (peerConnectionRef.current.remoteDescription) {
            peerConnectionRef.current.addIceCandidate(candidate);
          } else {
            setIceCandidatesQueue(queue => [...queue, candidate]);
          }
        }
      });
    });
  };

  return (
    <div className="videowindow">
      <div className="video-container">
        <video ref={webcamVideoRef} autoPlay muted></video>
        <video ref={remoteVideoRef} autoPlay></video>
      </div>
      <div className="input-container">
        <input 
          ref={callInputRef} 
          type="text" 
          placeholder="Call ID" 
          onChange={(e) => setCallId(e.target.value)} 
        />
      </div>
      <div>
        <button 
          ref={webcamButtonRef} 
          onClick={handleWebcamButtonClick}
        >
          Start Webcam
        </button>
        <button 
          ref={callButtonRef} 
          onClick={handleCallButtonClick}
        >
          Call
        </button>
        <button 
          ref={answerButtonRef} 
          onClick={handleAnswerButtonClick}
        >
          Answer
        </button>
      </div>
    </div>
  );
};

export default VideoCall;

I have tried changing the logic, but cannot see where the issue is.

Hide menu (navbar) when scrolling, by different amount of pixels in different media queries

My navbar hides when scrolling down by 96px because that’s its height on large screens.
Scrolling up causes the navbar to return.

However, the navbar height will change at different breakpoints and I will have to modify the script.

The problem is that I don’t know javascript, jquery or any other programming language at all. I copied the script and only changed the number of pixels in it. Could someone write me a ready-made script to change the value?

I’m creating a website for the company I work for and I really need it. I would be very grateful!

<script>
var prevScrollpos = window.pageYOffset;
window.onscroll = function() {
var currentScrollPos = window.pageYOffset;
  if (prevScrollpos > currentScrollPos) {
    document.getElementById("navbar").style.top = "0";
  } else {
    document.getElementById("navbar").style.top = "-96px";
  }
  prevScrollpos = currentScrollPos;
}
</script>

I looked at this page:

https://www.w3schools.com/howto/howto_js_media_queries.asp

But I won’t get anything out of it because, as I wrote earlier, I don’t know anything about programming

JavaScript function not working when called to an include html code file

I have a webpage where I want to include footer from external footer html file using (w3-include). The footer also has its own JavaScript file. Inside the footer, I have a dialog box that pops for users to subscribe. The footer is working alright but the JavaScript function is not working when I click on the subscribe button to display the dialog.

here is the main html file

<body>
 <section class="related">
     <div class="rpst"> 
    --- some text here ----
     </div>
  </section>

  <div w3-include-html="footer.html"></div>

    <script src="subscribeDialog.js"></script>
    <script src="include.js"></script>

   <script>includeHTML();</script>

</body>

Here is the footer.html


<section class="footer">
  
  <div class="box-container">
    
--- footer contents here ----

  </div>

      <div class="column_2">
        <div class="dialog">
           <div class="header">
              <p>Subscribe to our newsletter</p>
              <i class="fas fa-times" id="closeDialog"></i>
          </div>
          <section class="subs">
              <div class="subs-inputBox">
                  <form action="subscribe_submit.php" method="POST" autocomplete="off">
                      <div class="subs-inputBox">
                          <div class="form-group">
                          <input name="subs_email" type="email" required class="form-control" id="email" placeholder="Enter email"/>
                          <button class="btn btn-primary" type="submit" name="sendmail" value="Send">Submit</button>
                      </div>
                  </form>
              </div>
          </section>
        
        </div> 
    
        <div class="subContainer">
            <h2>Subscribe to our newsletter</h2>
            
            <h1 id="openDialog">subscribe</h1>
        </div>
      </div>
    </section>
  
</div>

</section>

<script src="subscribeDialog.js"></script>

Here is the subscribeDialog.js

let d = document.querySelector(".dialog");
let openSubX = document.querySelector("#openDialog");
let closeSubX = document.querySelector("#closeDialog");

const closeDialog = ()=>{
    d.style.visibility="hidden";
};

openDialog.addEventListener("click", ()=>{
    d.style.visibility="visible";
    console.log("working");
});

closeDialog.addEventListener("click", ()=>{
    closeDialog();
    console.log("working");
});

I have been working on this error for some days now but to no avail. Anytime I click on the subscribe button it stays unchanged thus nothing happens, which I want it to open the dialog when click.

I got something similar to my case but still doesn’t work at my end.

Attaching Zoom in/out functionality to buttons [duplicate]

I’ve added a zoom in and out functionality to my art portfolio. I’ve build it using Framer and and im using code override to make sure the zoom in and out functionality works. It does seem to work (through using scrolling up and down). But the code also features a override for 2 buttons on the page which when clicking on them should zoom in and out of the canvas, this is not working at the moment and I cant seem to figure out why.

I’m using the following code snippet to zoom in and out of the canvas:

import { useState, useEffect } from "react"
import { Override, Data } from "framer"

const zoomData = Data({
    scale: 1,
    zoomSpeed: 0.05,
    minZoom: 0.5,
    maxZoom: 3,
})

export function useZoomableCanvas(): Override {
    const [scale, setScale] = useState(zoomData.scale)

    // Function to handle wheel zoom
    useEffect(() => {
        const handleWheel = (event) => {
            event.preventDefault() // Prevent default scrolling behavior

            if (event.deltaY < 0) {
                // Zoom in
                setScale((prevScale) =>
                    Math.min(prevScale + zoomData.zoomSpeed, zoomData.maxZoom)
                )
            } else {
                // Zoom out
                setScale((prevScale) =>
                    Math.max(prevScale - zoomData.zoomSpeed, zoomData.minZoom)
                )
            }
        }

        window.addEventListener("wheel", handleWheel, { passive: false })

        return () => {
            window.removeEventListener("wheel", handleWheel)
        }
    }, [])

    // Zoom in function for buttons
    const zoomIn = () => {
        setScale((prevScale) =>
            Math.min(prevScale + zoomData.zoomSpeed, zoomData.maxZoom)
        )
    }

    // Zoom out function for buttons
    const zoomOut = () => {
        setScale((prevScale) =>
            Math.max(prevScale - zoomData.zoomSpeed, zoomData.minZoom)
        )
    }

    return {
        style: {
            transform: `scale(${scale})`,
            transition: "transform 0.3s ease",
        },
        onClickZoomIn: zoomIn,
        onClickZoomOut: zoomOut,
    }
}

// Button overrides for zoom in/out
export function ZoomInButton(): Override {
    const { onClickZoomIn } = useZoomableCanvas()
    return {
        onTap: onClickZoomIn,
    }
}

export function ZoomOutButton(): Override {
    const { onClickZoomOut } = useZoomableCanvas()
    return {
        onTap: onClickZoomOut,
    }
}

The “UseZoomableCanvas” works, but the other 2 functions are not working “ZoomInButton” & “ZoomOutButton”.

This is the URL i’m working on https://www.jesper.studio/playground/visual-summaries

Could someone help me with this?

I’ve tried to sort it out using various AI assistents, but I cant seem to get it to work.

JS Alert on pageload

How do I convert this piece of code into an alert that pops up after page has loaded?

I want to convert this button into an alert / message that pops up after the page has loaded.

I tried integrating it via “body onlaod” into the page code.

<body onload="geoFindMe()"> 
<article>  
<h2>Geolocate</h2>

<button id="find-me">Show the location</button><br />
<p id="status"></p>
<a id="map-link" target="_blank"></a>
</main>
</article>   
</div>

Here ist the script for the geolocation that I want to be
displayed in the alert.

<script>
  function geoFindMe() {
    const status = document.querySelector("#status");
    const mapLink = document.querySelector("#map-link");

    mapLink.href = "";
    mapLink.textContent = "";

    function success(position) {
      const latitude = position.coords.latitude;
      const longitude = position.coords.longitude;

      status.textContent = "";
      mapLink.href = `https://www.openstreetmap.org/#map=18/${latitude}/${longitude}`;
      mapLink.textContent = `Breitengrad: ${latitude} °, Längengrad: ${longitude} °`;
    }

    function error() {
      status.textContent = "Unable to retrieve your location";
    }

    if (!navigator.geolocation) {
      status.textContent = "Geolocation is not supported by your browser";
    } else {
      status.textContent = "Locating…";
      navigator.geolocation.getCurrentPosition(success, error);
    }
  }

  document.querySelector("#find-me").addEventListener("click", geoFindMe);
</script>

</body>

Problem to send my formData instance via axios with content-type multipart/form -data

I’m working on vue3 and I want to send my form data which may contain a file image to my API via axios request but I still have a problem. If I inspect the formData instance, all values ​​are present but are ignored when my axios Content-Type header are set to multipart/form-data. I also use Pinia in my work to store my functions. Can someone help me please?

My Pinia function

async createEnterprise(data) {
        
    const formData = new FormData();
    formData.append("logo", data.value.logo, data.value.logo.name);
    formData.append("name", data.value.name);
    formData.append("email", data.value.email);
    formData.append("phone", data.value.phone);
    formData.append("address", data.value.address);
            
    try {
       const response = await axios.post('/api/auth/entreprises/store', formData, {
             headers: {
                 "Authorization": `Bearer ${localStorage.getItem('token')}`,
                 "Content-Type": "multipart/form-data",
                 "Accept": "application/json"
                    },
                  data: formData
           }) 

       const data = await response.data;
                
    } catch (error) {
        this.errors = error.response.data.errors;            
    }
},

My create view in vue

const data = ref({
        name: "",
        email: "",
        phone: "",
        address: "",
        logo: null
    });

    const handleFileChange = (event) => {
        let logo = event.target.files[0];
        data.value.logo = logo;
    }

    const submitForm = async () => {
        try {
            await createEnterprise(data);
        } catch (error) {
            console.log("Error submitting form: " + error);
        }
    }

<form @submit.prevent="submitForm">
     <div class="create__form__group">
          <label for="logo" class="create__label">Logo:</label>
          <p class="text-sm opacity-75 indent-3">Cliquer dans le vide pour charger le logo</p>
          <label class="create__file__label border border-gray-200 hover:border-4 hover:border-blue-200">
               <div class="file__upload__icon">
                   <svg xmlns="http://www.w3.org/2000/svg" width="100" height="100" viewBox="0 0 24 24"      fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" 
stroke-linejoin="round" class="feather feather-image">
            <rect x="3" y="3" width="18" height="18" rx="2" ry="2"></rect>
                                                <circle cx="8.5" cy="8.5" r="1.5"></circle>
                                                <polyline points="21 15 16 10 5 21"></polyline>
                                            </svg>
                                        </div>
             <input type="file" accept="image/*" class="focus:outline-none focus:ring focus:ring-blue-200"
                                        @change="handleFileChange">
             <p class="file__info">Aucun fichier sélectionné</p>
          </label>
          <p class="error" v-if="enterprisesStore.errors.logo">{{ enterprisesStore.errors.logo[0] }}</p>
                                    
     </div>   
</form>

When I submit the form, the result of the data still empty with all fields input filled, That means the input fields values are not sent

how do check after every 24 hourse is day changed to new date or no in js or node js

how do check after every 24 hourse is day changed to new date or no in js or node js

how do check after every 24 hourse is day changed to new date or no in js or node js

how do check after every 24 hourse is day changed to new date or no in js or node js

how do check after every 24 hourse is day changed to new date or no in js or node js

how do check after every 24 hourse is day changed to new date or no in js or node js
how do check after every 24 hourse is day changed to new date or no in js or node js
how do check after every 24 hourse is day changed to new date or no in js or node js
how do check after every 24 hourse is day changed to new date or no in js or node js
how do check after every 24 hourse is day changed to new date or no in js or node js
how do check after every 24 hourse is day changed to new date or no in js or node js
how do check after every 24 hourse is day changed to new date or no in js or node js
how do check after every 24 hourse is day changed to new date or no in js or node js
how do check after every 24 hourse is day changed to new date or no in js or node js
how do check after every 24 hourse is day changed to new date or no in js or node js
how do check after every 24 hourse is day changed to new date or no in js or node js
how do check after every 24 hourse is day changed to new date or no in js or node js
how do check after every 24 hourse is day changed to new date or no in js or node js
how do check after every 24 hourse is day changed to new date or no in js or node js
how do check after every 24 hourse is day changed to new date or no in js or node js
how do check after every 24 hourse is day changed to new date or no in js or node js
how do check after every 24 hourse is day changed to new date or no in js or node jshow do check after every 24 hourse is day changed to new date or no in js or node js

how do check after every 24 hourse is day changed to new date or no in js or node js

how do check after every 24 hourse is day changed to new date or no in js or node js

how do check after every 24 hourse is day changed to new date or no in js or node js

how do check after every 24 hourse is day changed to new date or no in js or node js
how do check after every 24 hourse is day changed to new date or no in js or node js
how do check after every 24 hourse is day changed to new date or no in js or node js
how do check after every 24 hourse is day changed to new date or no in js or node js
how do check after every 24 hourse is day changed to new date or no in js or node js
how do check after every 24 hourse is day changed to new date or no in js or node js
how do check after every 24 hourse is day changed to new date or no in js or node js
how do check after every 24 hourse is day changed to new date or no in js or node js
how do check after every 24 hourse is day changed to new date or no in js or node js
how do check after every 24 hourse is day changed to new date or no in js or node js
how do check after every 24 hourse is day changed to new date or no in js or node js
how do check after every 24 hourse is day changed to new date or no in js or node js
how do check after every 24 hourse is day changed to new date or no in js or node js
how do check after every 24 hourse is day changed to new date or no in js or node js
how do check after every 24 hourse is day changed to new date or no in js or node js
how do check after every 24 hourse is day changed to new date or no in js or node js
how do check after every 24 hourse is day changed to new date or no in js or node jshow do check after every 24 hourse is day changed to new date or no in js or node js

how do check after every 24 hourse is day changed to new date or no in js or node js

how do check after every 24 hourse is day changed to new date or no in js or node js

how do check after every 24 hourse is day changed to new date or no in js or node js

how do check after every 24 hourse is day changed to new date or no in js or node js
how do check after every 24 hourse is day changed to new date or no in js or node js
how do check after every 24 hourse is day changed to new date or no in js or node js
how do check after every 24 hourse is day changed to new date or no in js or node js
how do check after every 24 hourse is day changed to new date or no in js or node js
how do check after every 24 hourse is day changed to new date or no in js or node js
how do check after every 24 hourse is day changed to new date or no in js or node js
how do check after every 24 hourse is day changed to new date or no in js or node js
how do check after every 24 hourse is day changed to new date or no in js or node js
how do check after every 24 hourse is day changed to new date or no in js or node js
how do check after every 24 hourse is day changed to new date or no in js or node js
how do check after every 24 hourse is day changed to new date or no in js or node js
how do check after every 24 hourse is day changed to new date or no in js or node js
how do check after every 24 hourse is day changed to new date or no in js or node js
how do check after every 24 hourse is day changed to new date or no in js or node js
how do check after every 24 hourse is day changed to new date or no in js or node js
how do check after every 24 hourse is day changed to new date or no in js or node jshow do check after every 24 hourse is day changed to new date or no in js or node js

how do check after every 24 hourse is day changed to new date or no in js or node js

how do check after every 24 hourse is day changed to new date or no in js or node js

how do check after every 24 hourse is day changed to new date or no in js or node js

how do check after every 24 hourse is day changed to new date or no in js or node js
how do check after every 24 hourse is day changed to new date or no in js or node js
how do check after every 24 hourse is day changed to new date or no in js or node js
how do check after every 24 hourse is day changed to new date or no in js or node js
how do check after every 24 hourse is day changed to new date or no in js or node js
how do check after every 24 hourse is day changed to new date or no in js or node js
how do check after every 24 hourse is day changed to new date or no in js or node js
how do check after every 24 hourse is day changed to new date or no in js or node js
how do check after every 24 hourse is day changed to new date or no in js or node js
how do check after every 24 hourse is day changed to new date or no in js or node js
how do check after every 24 hourse is day changed to new date or no in js or node js
how do check after every 24 hourse is day changed to new date or no in js or node js
how do check after every 24 hourse is day changed to new date or no in js or node js
how do check after every 24 hourse is day changed to new date or no in js or node js
how do check after every 24 hourse is day changed to new date or no in js or node js
how do check after every 24 hourse is day changed to new date or no in js or node js
how do check after every 24 hourse is day changed to new date or no in js or node jshow do check after every 24 hourse is day changed to new date or no in js or node js

how do check after every 24 hourse is day changed to new date or no in js or node js

how do check after every 24 hourse is day changed to new date or no in js or node js

how do check after every 24 hourse is day changed to new date or no in js or node js

how do check after every 24 hourse is day changed to new date or no in js or node js
how do check after every 24 hourse is day changed to new date or no in js or node js
how do check after every 24 hourse is day changed to new date or no in js or node js
how do check after every 24 hourse is day changed to new date or no in js or node js
how do check after every 24 hourse is day changed to new date or no in js or node js
how do check after every 24 hourse is day changed to new date or no in js or node js
how do check after every 24 hourse is day changed to new date or no in js or node js
how do check after every 24 hourse is day changed to new date or no in js or node js
how do check after every 24 hourse is day changed to new date or no in js or node js
how do check after every 24 hourse is day changed to new date or no in js or node js
how do check after every 24 hourse is day changed to new date or no in js or node js
how do check after every 24 hourse is day changed to new date or no in js or node js
how do check after every 24 hourse is day changed to new date or no in js or node js
how do check after every 24 hourse is day changed to new date or no in js or node js
how do check after every 24 hourse is day changed to new date or no in js or node js
how do check after every 24 hourse is day changed to new date or no in js or node js
how do check after every 24 hourse is day changed to new date or no in js or node jshow do check after every 24 hourse is day changed to new date or no in js or node js

how do check after every 24 hourse is day changed to new date or no in js or node js

how do check after every 24 hourse is day changed to new date or no in js or node js

how do check after every 24 hourse is day changed to new date or no in js or node js

how do check after every 24 hourse is day changed to new date or no in js or node js
how do check after every 24 hourse is day changed to new date or no in js or node js
how do check after every 24 hourse is day changed to new date or no in js or node js
how do check after every 24 hourse is day changed to new date or no in js or node js
how do check after every 24 hourse is day changed to new date or no in js or node js
how do check after every 24 hourse is day changed to new date or no in js or node js
how do check after every 24 hourse is day changed to new date or no in js or node js
how do check after every 24 hourse is day changed to new date or no in js or node js
how do check after every 24 hourse is day changed to new date or no in js or node js
how do check after every 24 hourse is day changed to new date or no in js or node js
how do check after every 24 hourse is day changed to new date or no in js or node js
how do check after every 24 hourse is day changed to new date or no in js or node js
how do check after every 24 hourse is day changed to new date or no in js or node js
how do check after every 24 hourse is day changed to new date or no in js or node js
how do check after every 24 hourse is day changed to new date or no in js or node js
how do check after every 24 hourse is day changed to new date or no in js or node js
how do check after every 24 hourse is day changed to new date or no in js or node js

best way to store user data for a html / js website? [closed]

building a basic forum website from scratch and was wondering what was the best way to go about storing the users data, eg: usernames and passwords for sign up forums and then accessing them when logging in again?
(im using js and html)

i tried using local storage as a temporary solution but this wont be used for long term use, ive looked a little bit into using something like mongo db or my sql but never found a good guide on how to use them and what their use cases are for.

setInterval is slower when the page isn’t focused [duplicate]

I have a function that looks through a given page’s DOM for a string. If it finds it, it reloads a page after a randomized amount of seconds have passed. If it doesn’t find the given string, the page stops refreshing.

The function is the following:


function reloadPage() {
  const getRandomNumber = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;
  const LookFor = "test string";
  const interval = getRandomNumber(0, 2);

  const intervalHandle = setInterval(function () {

    if($('body:contains("' + LookFor + '")').length > 0) {
        clearInterval(intervalHandle); // Or else it tries to reload when it's already reloading
        window.location.reload();
    } else {
        clearInterval(intervalHandle);
    }

  }, interval *1000);
};

It works well enough when the page the code is getting executed on is focused, but when the page isn’t focused, it can take many times over the expected window of time for the refresh to happen. On average, I get a page refresh every 1.29 seconds when the window is focused, and ~15 seconds when the page isn’t focused. Sometimes, it’ll even refresh as soon as I focus back on the page the code is getting run in.

I saw on this answer that JS interval handles go slower on inactive pages for browser performance reasons. Is there a way to make the page always refresh at the set time interval, between 0-2 seconds, regardless of page focus?

How can I use gsap.registerEffect correctly?

I have a problem recording an effect with gsap,
I create an animation template in a js file: “gsapEffect.js”, import it into my app.jsx and effect remains inaccessible, could you better explain to me how it works?

my gsapEffect.js file :

import gsap from "gsap";

gsap.registerEffect({
    name: "backgroundOpening",
    effect: (direction,targets, ...config) => {

        const animationType = config.direction === "from" ? gsap.from : gsap.to;

        return animationType(targets, {
            top: config.top,
            duration: config.duration,
            ease: config.ease,
        });
    },
    defaults: { duration: 0.4, top:"-100%", ease: 'power2.inOut', direction: "to" },
    extendTimeline: true
});

I import it in my app.jsx :

import "./customFunctions/gsapEffect.js"

and use it in my componenent juste like that :

import { h } from 'preact';
import { MenuDialogContent } from "./MenuDialogContent.jsx";
import useStore from "../store/store.js";
import { useEffect } from "preact/hooks";
import { gsap } from "gsap";

export function Menu() {
    const { activeMenu, setActiveMenu } = useStore();

    const setMenuBackgroundAnimation = (tl, yBackgroundAnimationValue) => {
        return tl.to(".menu", {
            top: yBackgroundAnimationValue,
            duration: 0.4,
            ease: 'power2.inOut',
        });
    };

    const setMenuTextAnimation = (tl, yTextAnimationValue, isEntering) => {
        return tl.to('.menu-anim li', {
            top: yTextAnimationValue,
            opacity: isEntering ? 1 : 0,
            stagger: 0.08,
            ease: isEntering ? 'power4.in' : 'power4.out',
            duration: 0.1
        });
    };

    useEffect(() => {
        const tl = gsap.timeline();

        if (activeMenu) {
            tl.backgroundOpening('.menu', {
                duration: 0.4,
                ease: 'power2.inOut',
                top: 0
            });

            setMenuTextAnimation(tl, 0, true);
        } else {
            setMenuTextAnimation(tl, '-5vh', false);
            setMenuBackgroundAnimation(tl, '-100vh');
        }
    }, [activeMenu]);

    return (
        <>
      <span className={`font-bold`} onClick={() => setActiveMenu(!activeMenu)}>
        <button className={activeMenu ? "dots on" : "dots"}>
          <span></span>
        </button>
      </span>
            <MenuDialogContent argSetter={setActiveMenu} trigger={activeMenu} />
        </>
    );
}

Symbol.iterator mysteriously changes to null or undefined upon calling

I have a JavaScript class that wraps an array. The class looks something like this.

class Store {
    constructor() {
        this._store = [];
    }
}

I am trying to define a Symbol.iterator, so a class instance can be iterated through with for example a for (... of ...) loop.

The class is designed in such a way, that the _store parameter can be null. My solution for defining Symbol.iterator function in compliance with this is as follows

class Store {
    ...

    [Symbol.iterator]() {
        return (this._store || [])[Symbol.iterator]();
    }
}

The idea behind this is, that if the _store holds an array, this code will return _store[Symbol.iterator], otherwise it will return iterator of an empty array.

If console.log-ged, the following expression appears to be a function, as expected.

console.log( (this._store || [])[Symbol.iterator] )

However, once this function is called, the following error is thrown, which points to the code which called the function.

TypeError: Cannot convert undefined or null to object

Any ideas to why this is happening?

How to update this to work with new MUI v6 Grid2?

I’m trying to update my project to the new Material UI v6 version, but I’m encountering layout issues after upgrading to the new Grid v2. The layout of the chart (and possibly other components) gets compressed and loses its full width. I tried removing the item property from the Grid, but that didn’t fix the issue.

I’m using Vite as the bundler and Material UI v6. Below is the code for my dashboard page:

import React from "react";
import Grid from "@mui/material/Grid";
import { Box, useMediaQuery, useTheme } from "@mui/material";
import PageContainer from "../../components/container/PageContainer";
import StockOverview from "./components/StockOverview";
import StockUnderSafety from "./components/StockUnderSafety";
import SalesOverview from "./components/SalesOverview";

const Dashboard = () => {
  const theme = useTheme();
  const isSmallScreen = useMediaQuery(theme.breakpoints.down("sm"));

  return (
    <PageContainer title="Dashboard" description="This is Dashboard">
      <Box
        sx={{
          display: "flex",
          justifyContent: "center",
          alignItems: "center",
          minHeight: "100vh",
          padding: isSmallScreen ? theme.spacing(2) : theme.spacing(8),
        }}
      >
        <Grid container spacing={2} maxWidth={"100%"}>
         
          <Grid item xs={12} lg={8}>
            <SalesOverview />
          </Grid>

          
          <Grid item xs={12} lg={4} container direction="column" spacing={2}>
            <Grid item>
              <StockOverview />
            </Grid>
            <Grid item>
              <StockUnderSafety />
            </Grid>
          </Grid>
        </Grid>
      </Box>
    </PageContainer>
  );
};
export default Dashboard;







[[enter image description here](https://i.sstatic.net/rEbr93ik.png)](https://i.sstatic.net/LML2VBdr.png)

The problem is that after updating to the new Grid v2, the chart layout shrinks, especially in width. I tried removing the item property from the Grid, but nothing changed. Here's an image showing the issue.

Environment:

Material UI v6
Vite
React
Any suggestions on how to resolve this problem are appreciated.