What’s the best way to create a mutex lock in JavaScript?

So far I have created a function used to set a timeout to simulate a mutex. I’m thinking there has to be a better way to do this though, maybe a built in function?

function RenderTreeMutex() {
    if(rendering || dragging || resetting) {
        setTimeout(RenderTreeMutex, 50);
        return;
    }
  }

This method seems a bit unorthodox, there must be a cleaner way?

Good luck with that one is pawrfoll

New geem to promote

Financial services good network maining token maining app Turn your sestam check out the email to promote the same thing about my account KYC approved please help recowist me know what playing with my account rajistar 8

How can I know when a child element is created on a parent element in javascript/typescript?

I have three custom components, MyParentElement and MyChildElement1 and MyChildElement2:

class MyParentElement extends HTMLElement 
{
  connectedCallback() 
  {
    console.log('MyParentElement connectedCallback()');
    for (let i = 0; i < this.children.length; ++i)
    {
      const elem = this.children[i];
      if (elem.tagName.toLowerCase() == 'my-child-element-1' || elem.tagName.toLowerCase() == 'my-child-element-2')
      {
        console.log(`elem.sortValue: ${elem.sortValue}`);
      }
    }

    setTimeout(() => 
    {
      for (let i = 0; i < this.children.length; ++i)
      {
        const elem = this.children[i];
        if (elem.tagName.toLowerCase() == 'my-child-element-1' || elem.tagName.toLowerCase() == 'my-child-element-2')
        {
          console.log(`elem.sortValue: ${elem.sortValue}`);
        }
      }
    }, 10);
  }
}
customElements.define("my-parent-element", MyParentElement);


class MyChildElement1 extends HTMLElement 
{
  constructor()
  {
    super();
    console.log(`MyChildElement1: ${this.sortValue}`);
  }

  get sortValue() { return 1; }
}
customElements.define("my-child-element-1", MyChildElement1);


class MyChildElement2 extends HTMLElement 
{
  constructor()
  {
    super();
    console.log(`MyChildElement2: ${this.sortValue}`);
  }

  get sortValue() { return 2; }
}

customElements.define("my-child-element-2", MyChildElement2);
<my-parent-element>
  <my-child-element-1></my-child-element-1>
  <my-child-element-2></my-child-element-2>
</my-parent-element>

When connectedCallback() is called for MyParentElement, sortValue gives me undefined. After the constructor is called for the two child elements, sortValue will work as expected.

Is there a way to know in the parent element when the child elements are ready without a timeout? MutationObserver didn’t seem to work for children that already exist as part of the HTML (but it will work if I create the elements and use appendChild(), however I am hoping to avoid that).

React Testing Library: Unable to find text in custom modal using MUI Dialog

I’m writing a test for a React component that shows an error modal when a fetch fails. The component internally uses a custom modal that wraps @mui/material/Dialog. Here’s a simplified version of my test:

it('should show error message when fetch fails', async () => {
  // simplified test
  fireEvent.click(searchButton);

  expect(screen.queryByText('[email protected]')).not.toBeInTheDocument();
  expect(screen.queryByText('Account Test')).not.toBeInTheDocument();

  await waitFor(() => {
    expect(screen.getByText(/Error fetching accounts/i)).toBeInTheDocument();
  });
});

The problem is that the test fails with the following error:

Unable to find an element with the text: Error fetching accounts. This could be because the text is broken up by multiple elements. In this case, you can provide a function for your text matcher to make your matcher more flexible.

Things I’ve tried:

  1. Using a regex:
const modalTitle = await screen.findByText(/Error fetching accounts/i);
expect(modalTitle).toBeInTheDocument();

Same error

  1. Using a custom function:
const modalTitle = await screen.findByText((content) =>
  content.includes('Error fetching accounts')
);
expect(modalTitle).toBeInTheDocument();

Error:

Unable to find an element with the text: (content) => content.includes('Error fetching accounts'). This could be because the text is broken up by multiple elements. In this case, you can provide a function for your text matcher to make your matcher more flexible.
  1. Querying the dialog by role:
const dialog = await screen.findByRole('dialog');
expect(within(dialog).getByText(/Error fetching accounts/i)).toBeInTheDocument();

Error:

Unable to find role="dialog"

I suspect the problem is that the modal is rendered asynchronously or in a portal (MUI Dialog uses ReactDOM.createPortal). How should I correctly test that the error message is displayed in a MUI Dialog using React Testing Library?

iOS 26: Camera video works but QR/barcode detection (zxing, html5-qrcode) silently fails in all browsers

My team has developed a web application that uses the device’s camera to decode QR codes and barcodes from labels. After the recent iOS 26 update, our application has completely stopped working on devices running this version of iOS. The camera feed works fine (video stream is visible), and we have confirmed that all necessary permissions are granted. However, the barcode/QR code detection engine fails silently, and we have been unable to identify a workaround so far.

Implementation Details:

  • Libraries Used: We are using the ZXing library and the html5-qrcode library for barcode/QR code scanning.

  • Affected Platform: The issue occurs only on iOS 26. Other iOS versions and Android devices work as expected.

  • Browsers Tested: We have tested the application on major browsers available on iOS, including Safari, Chrome, and Firefox. The issue persists across all browsers, so it does not appear to be specific to Safari.

  • Additional Testing: We attempted to disable QR code detection in the iPhone settings (Settings > Camera > Scan QR Codes), but this had no effect on the issue.

Problem:

  • The barcode/QR code detection fails without throwing any errors or logs, making it difficult to debug.
  • No workaround has been found yet.

Question:

Has anyone else encountered a similar issue with barcode/QR code detection on iOS 26 using ZXing or html5-qrcode libraries? If so, were you able to find a solution or workaround? Any insights or suggestions on how to debug or resolve this issue would be greatly appreciated.

Thank you!

*Cookies* sent by server is not Visible from frontEnd (CORS applicable)

The cookies created in server side(HTTP server) isnt visible to FrontEnd script
I have created an Array of Cookies using Set-Cookie inside createServer method

`res.setHeader('Set-Cookie',` [
        'sessionId=abc123; SameSite=None;Secure;',
        'username=ratul; SameSite=None;Secure;',
        'name=Ratul; SameSite=None;Secure;'
    `]);`

According to Cross Origin resource sharing if my domain or PORT is different then i have to used

`"Access-Control-Allow-Origin":'http://X.X.X.X:3000'
 "Access-Control-Allow-Methods": "GET, POST, OPTIONS",
 'Access-Control-Allow-Headers': 'Content-Type,user-agent,X-Client-Header',
 'Access-Control-Allow-Credentials': `'true'`

YES I Have used it and Since my frontend sending CORS request hence i have also used

`'credentials':'include'`

STILL
whensoever i do on (FrontEnd Script)
document.cookie
this gives empty string
OR
res.headers.get('Set-Cookie')
gives
null

I have attached my repo below
HTML_CSS_JS_PRACTICE/HTML_CSS_JS_30/PS3

The cookies sent from the HTTP server:
null

But why? I have done acess-control-allow-credentials:'True'
as Well as credentials:'include'
also exposed that header of set-cookie using access-control-allow-headers

Sorry if i have any misconceptions about HTTP Server headers and cookies
Thank you in advance!

Compress wav size in the javascript client

I am currently recording audio in wav from the browser in my Next application using an extension of the MediaRecorder.
I need the audio to be in wav format in order to use Azure speech services. However, I’d like to also store the audio in a bucket (S3 most likely) for the user to see listen to the audio later. For this I need to have the audio in a compressed format: mp3, webm whatever, because the wav files are too heavy

I was thinking in compressing server side, either in the plain backend or maybe on a lambda function, but it looked like overengineering or heavy processing on the backend.
So I was thinking on doing this compression in the client. How can I do that? The other solutions I found are really old. The only one kinda recent was Lamejs, but I’m not too sure on the state of that package.

JavaScript Array Object, return a keys value in new array [duplicate]

I have an array that contains an object. (I’ve simplified to explain);

playerDB_1 = [];
for(n=0; n<=1000; n++){ 
    playerDB_1[n] = {};
    playerDB_1[n].code = 1000+n;
};

I want to be create a new array with the values of each .code key, thus creating something, result_1 = [1000, 1001, 1002, 1003, 1004 etc.];

I have found this small snippet of code that explains how to do so:

const map = new Map([['key1', 'value1'], ['key2', 'value2']])
const valuesArray = Array.from(map.values())

console.log(valuesArray) // Output: ['value1', 'value2']

But I can’t figure out how to implement it on.

How can I detect if a browser is blocking a new tab or popup when using `window.open` with `noopener`?

Like suggested in the question How can I detect if a browser is blocking a popup? (2008), the return value of the JavaScript function call

window.open("https://example.com/", "_blank", "")

can be used to determine if the popup was blocked; as stated on MDN

null is returned if the browser fails to open the new browsing context, for example because it was blocked by a browser popup blocker.

However, this solution breaks due to the method always returning null when you use noopener under windowFeatures, which is also what you are generally almost always supposed to do when your project is intended for production. noopener is suggested in the question Use window.open but block use of window.opener (2016) to address a security concern.

So how can you still determine if a popup (e.g., opening a new tab) was blocked when calling the following in JavaScript:

window.open("https://example.com/", "_blank", "noopener")`

given that it always returns null?
(Tested in Chrome and Firefox, year 2025)

The MDN documentation doesn’t cover this case, so I fear this might be a bug / design flaw.

Motivation

To clarify an expected use-case, it’s typical for a web app’s functionality to break if any attempts to navigate a user to a different page/domain fail. Critical parts of a user flow may require developers to handle any failure by displaying a warning to the user and teaching them how to allow popups for the current site in their browser.

Note: you can also find this question in the form of a comment in:

Workaround:

This answer suggests a workaround, similar to what an the article Overcoming popup blocking issues (2023) also describes:

function dynamicallyCreateAnchorAndNavigate(url) {
  let a = document.createElement('a');
  a.href = url;
  a.target = "_blank"
  // Note: target="_blank" implies rel="noopener" behavior as per https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/a#browser_compatibility
  a.rel = "noopener"
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
}

By not using the window.open API, but instead creating a temporary anchor to use its click API, we may avoid some popup blockers.

I don’t know if this is currently a consistent solution across all typical environments and guarantees that no popup blockers will ever block the new page. If so, I think it would indicate a negligence of browsers’ implementations of popup blockers. I welcome any contributions/comments to please update these statements to reflect the current situation.

That said, I believe the Window API provides more functionality than <a>, so the window.open (being the topic of this question) may still be necessary for some use-cases. For example, the popup feature from windowFeatures, i.e. a “minimal popup window”, probably can’t be achieved via <a>.

Chrome extension’s content script trying to use MutationObserver but fails to detect nodes that i want to find

this Chrome extension content script is supposed to run on youtube and try to find elements with tagName YT-THUMBNAIL-VIEW-MODEL.
The script is injected at document_start so that it is executed and i catch every new element

but this is not detecting even a single node.
pls someone help

Note that given code is not wrapped in kind of evenListeners like load, DOMContentLoaded

Code:


function processNodes(nodes) {
    nodes.forEach(node => {
        if (node.nodeType === Node.ELEMENT_NODE && node.tagName === "YT-THUMBNAIL-VIEW-MODEL") {
            console.log(node);
        }
    });
}
    const observer = new MutationObserver((mutationsList, observer) => {
        for (const mutation of mutationsList) {
            if (mutation.type === 'childList' && mutation.addedNodes.length > 0) {
                processNodes(mutation.addedNodes);
            }
        }
    });


    const targetNode = document.documentElement;
    const config = { childList: true, subtree: true };

    observer.observe(targetNode, config);

I tried a bunch and also asked ais but no help.
was expecting to see new elements that are getting added initially and after I scroll.

React state don’t rerender the component on change?

I’m building a simple chat app in React with a custom hook that fetches chats from a service once a WebSocket client is connected.

The fetch succeeds and I can see the data in the console, but the component still renders chat as null. It only shows the data after I trigger another state update by clicking a button.

here is the useChat hook :

import { useEffect, useState } from "react";
import ChatService from "../services/chat-service";
import { Client } from "@stomp/stompjs";
import Conversation from "../entities/chat/Conversation";
import Account from "../entities/user/Account";
import Message from "../entities/chat/Message";

export default function useChat(){
  const [loading,setLoading] = useState(true)
  const [client,setClient] = useState<Client | null>(null)
  const [chat,setChat] = useState<Conversation[] | null>(null);
  
  useEffect(()=>{
    const initSocket = async ()=>{
      const client = await ChatService.initialSocketConnnection((message)=>{
        console.log(message);
      })
      setClient(client)
    }
    initSocket()
    
    return ()=>{
      client?.deactivate();
      setClient(null);
    }
  },[])
  
  useEffect(()=>{
    if (!client) return;
    
    
    const initChat = async ()=>{
      const chats = await ChatService.getChat()
      console.log('Fetched chats:', chats);
      setChat(chats);
      setLoading(false)
    }
    
    initChat()
    
    return ()=>{
      setChat(null);
      setLoading(true)
    }
  }, [client])
  
  const sendMessage = (destination:Account,message:Message) => {
    if(!client) return
    ChatService.sendMessage(destination.username,message,client);
  }
  
  return {sendMessage,loading,chat}
}

and here is the Chat component

import { useState } from "react"
import Card from "../components/ui/Card"
import useChat from "../hooks/useChat"

export default function Chat(){
    const {sendMessage,loading,chat} = useChat()
    const [test,setTest]= useState<number | undefined>(0);
    
    if(loading) return <>Loading</>
    return <div className="w-full h-full bg-background-light dark:bg-background-dark flex ">
                <div className="w-2/6 h-full min-w-100 max-w-140 border-r border-border-light dark:border-border-dark flex flex-col">
                    <div className="w-full border-b border-border-light dark:border-border-dark p-4 flex items-center justify-between">
                        <h1 className="text-xl font-semibold ">Messages</h1>
                        <Card className="px-2 py-1 shadow-none border-none *:cursor-pointer">
                            <button  className="text-xl ">
                                <i className="fa-solid fa-plus"></i>
                            </button>
                        </Card>
                    </div>
                    <div className="flex-1 overflow-scroll ">
                        {loading?"loading":"not Loading"}
                        {Array.isArray(chat) && chat.length > 0 ? (
                            chat.map((element, index) => (
                                <h1 key={index}>{JSON.stringify(element)}</h1>
                            ))
                            ) : (
                            <p>No chats yet</p>
                            )}
                        
                        {test}
                        <br></br>
                        <button onClick={()=>{setTest(chat?.length)}}>
                            Increment
                        </button>
                    </div>
                </div>
                <div className="flex-1 h-full">
                  
                </div>

        </div>
}

When using this with and redirect back to the page after successful operation the ckeditor is not loading

I Am using ckeditor 5 and here is my configuration. which is working good when i first load the page but i click on the submit button and server redirect me on same page this is no longer working here.

<script type="importmap">
    {
        "imports": {
            "ckeditor5": "{{ asset('assets/ckeditor5/ckeditor5.js') }}",
            "ckeditor5/": "{{ asset('assets/ckeditor5/') }}"
        }
    }
</script>
<script type="module">
    import {
        ClassicEditor,
        AccessibilityHelp,
        Alignment,
        AutoLink,
        Autosave,
        BlockQuote,
        Bold,
        CodeBlock,
        Essentials,
        Font,
        GeneralHtmlSupport,
        Heading,
        HorizontalLine,
        Indent,
        IndentBlock,
        Italic,
        Link,
        Paragraph,
        SelectAll,
        Style,
        Table,
        TableCaption,
        TableCellProperties,
        TableColumnResize,
        TableProperties,
        TableToolbar,
        Undo
    } from 'ckeditor5';

    let ckEditors = document.querySelectorAll(".ckeditor");

    ckEditors.forEach((editor) => {
        ClassicEditor
            .create(editor, {
                plugins: [AccessibilityHelp, Alignment,
                    AutoLink,
                    Autosave,
                    BlockQuote,
                    Bold,
                    CodeBlock,
                    Essentials,
                    Font,
                    GeneralHtmlSupport,
                    Heading,
                    HorizontalLine,
                    Indent,
                    IndentBlock,
                    Italic,
                    Link,
                    Paragraph,
                    SelectAll,
                    Style,
                    Table,
                    TableCaption,
                    TableCellProperties,
                    TableColumnResize,
                    TableProperties,
                    TableToolbar,
                    Undo
                ],
                toolbar: {
                    items: ['undo',
                        'redo',
                        '|',
                        'bold',
                        'italic',
                        '|',
                        '|',
                        'heading',
                        '|',
                        'fontSize',
                        'fontFamily',
                        'fontColor',
                        'fontBackgroundColor',
                        '|',
                        'indent',
                        'outdent',
                        'alignment',
                        '|',
                        'horizontalLine',
                        'link',
                        'insertTable',
                        'blockQuote',
                        '|',


                    ]

                }
            })
            .then(editor => {
                window.editor = editor;
            })
            .catch(error => {
                console.error(error);
            });
    });
</script>

When redirect back to the page it gives me error

Error

Uncaught TypeError: The specifier “ckeditor5” was a bare specifier, but was not remapped to anything. Relative module specifiers must start with “./”, “../” or “/”.

How to do custom plugin with custom parameters?

We have a TypeDoc custom plugin called CustomPlugin and I wish to pass custom parameters into that plugin, therefore it appears I cannot add its name as a string to the plugin option.

After running Appplication.bootstrapWithPlugins, I call the plugin as a function CustomPlugin(params). The issue I am having is my plugin requires that the JSON output has already been written and is accessible for use inside the plugin. The JSON output can only be called after convert is called and the project instance becomes available.

app.convert.addUnknownSymbolResolver has to be set before app.convert() is called or the plugin will fail to resolve these unknown symbols. I have set this inside the CustomPlugin.

This is a NX Monorepo with multiply projects inside and TypeDoc is called against many of them in the right order using dependsOn in nx.json.

const app = await Application.bootstrapWithPlugins({
  { ...options },
  [...readers]
});

// I need the generated **my-path.json** available in here to access the symbolIdMap
// We actually also use other projects **my-path.json** as well in here
// We build the projects in the right order using dependOn in the nx.json file
load(params); // CustomPlugin

const project = app.convert();

await app.generateJson(project, 'my-path.json');

I have implemented a double pass which works fine but was looking for other solutions.

Sound delay on the npm module node-wav-player

I’m using a typewriter effect and want to make a sound for every letter like the movie letter sound. I want to use the CMD program in Windows 11 to make a chatbot that runs with the command node chatbot.js. I don’t want it to run in the browser but in node.js. I have tryed to ask the ChatGPT but with no luck. I’m using the node-wav-player and it works; but the sound is delayed and not stabile. On the repo on GitHub they mention the require method; but I want the import method.