Functions overlap in for loop javascript [duplicate]

I’m a beginner in js, and I’m making that Simon Says game. I’ve made a loop to show the previous sequence, but there’s a problem with the execution. I want it to show the sequence from the beginning, but when there are more colors in the gamePattern array, patClr value is last color and it just repeats the same one. The problem is that the function first does it’s thing, and sets the patClr to the last value in the array, and then does the functions that are in the setTimeout.

this is the code i made:

function showSequence(){
    $("h1").text("Level " + level);
    wait = 1000;
    for (var i = 0; i < gamePattern.length; i++){
        var patClr = gamePattern[i];
        var patBtn = $("#" + patClr);
        setTimeout(function(){
            playSound(patClr);
            buttonAnimation(patBtn, patClr);
        }, wait);
        wait = wait + 600;
    }
    setTimeout(function(){
        nextSequence();
    }, wait);
}

I’m sure there’s a much better way for this, but I couldn’t find it.

How to write this jquery into real javascript? [duplicate]

This is the code of Jquery:-
$(“#downloadRecording”).attr({ href: url, download: ‘test.mp3’ }).show();

Basically I am making audio recorder with the help of WebRTC. This code I saw in github. But I like coding in javascript. So please help me out from this problem.

Convert this into simple and real javascript

How to get specific page and store it in a variable in Google Apps Script?

Is there a simple way of accessing a page of Google Document in Google Apps Script and storing it in a variable? I need to insert an image in the beginning of each page (probably, PageBreak could be used as a page separator).

It should look something like this:

var image = textDocument[pageNumber].getChild(0).asParagraph().appendInlineImage(link.getBlob());

How could textDocument[pageNumber] (which should return a page of a text document) be achieved in Google Script?

How to convert the following vue.config.js into a vite.config.js file?

I have the below code and I would like to know how I may convert it so there would be no issue with using it in a vite.config.js file. As of now, using it as a vite.config.js file gives me errors relating to ‘module’ so I gathered that I may need to convert.

Is there documentation for converting between the two?

Also, is it possible in a vite project, to simply use both a vite.config and vue.config file?

const BundleTracker = require('webpack-bundle-tracker');

module.exports = {
    publicPath: "http://0.0.0.0:8080",
    outputDir: "./dist/",

    chainWebpack: config => {
        config.optimization.splitChunks(false)

        config.plugin('BundleTracker').use(BundleTracker, [
            {
                filename: './webpack-stats.json'
            }
        ])

        config.resolve.alias.set('__STATIC__', 'static')

        config.devServer
            .public('http://0.0.0.0:8080')
            .host('0.0.0.0')
            .port(8080)
            .hotOnly(true)
            .watchOptions({poll: 1000})
            .https(false)
            .headers({'Access-Control-Allow-Origin': ['*']})
    }
};

ref is stacking in sockets react native

Im trying to build chat application using sockets and everything is working except when im trying to add new session I beilieve it is stacking the reference but I don’t know what I’m missing

here is my code

    const [sessions, setSessions] = useState([]);
    const userSocketRef = useRef(null);

    useEffect(() => {
        async function getUser() {
            const user = await authStorage.getUser();
            const URL = "ws://192.168.1.176:3001/" + "users";
            if (userSocketRef.current === null) {
                userSocketRef.current = io(URL, {
                    auth: { user: user.uuid },
                    transports: ["polling", "websocket"],
                });
                userSocketRef.current.on("disconnect", () => {
                    console.log("disconnected");
                });
                userSocketRef.current.on("connect", () => {
                    console.log("connected");
                });
                userSocketRef.current.onAny((event, ...args) => {
                    console.log("event");
                });
                userSocketRef.current.on("connect_error", (err) => {
                    console.log("connect_error");
                });
            }
        }
        console.log("current sessions after handle: "+Object.keys(sessions))
        getUser();
        if (userSocketRef.current !== null ) {
            userSocketRef.current.on(
                "private message",
                (message, sessionUuid) => {
                    console.log("private message");
                    handleUpdateSession(message, sessionUuid);
                }
            );
            userSocketRef.current.on("new session", async (session) => {
                console.log(Object.keys(sessions));
                console.log(Object.keys(session));
                await handleNewSession(session);
            });

            
        }
    }, [sessions]);

    useEffect(() => {
        async function getSessions() {
            const user = await authStorage.getUser();
            const ret = await getUserSessions(user?.uuid);
            setSessions(ret.data.reverse());
        }
        getSessions();
    }, []);

    const handleNewSession = async (newSession) => {
        console.log("current sessions: " + Object.keys(sessions));
        console.log("new session: " + Object.keys(newSession));
        setSessions([newSession, ...sessions]);
    };
    const handleUpdateSession = (message, sessionUuid) => {
        try {
            console.log(sessionUuid, Object.keys(sessions));
            const temp = sessions;
            const session = temp.find((s) => s.uuid === sessionUuid);
            session.messages.push(message);
            const filteredSessions = temp.filter((s) => s.uuid !== sessionUuid);
            setSessions([session, ...filteredSessions]);
        } catch (error) {
            console.log(error);
        }
    };

now when i try to open new session it works great and I can send messages but when the user tries to send message it duplicates so many times and it gets errors because they are the same key I tried to debug and here is my conclusion

 LOG  current sessions after handle:
 LOG  current sessions after handle:
 LOG  connected
 LOG  event
 LOG  []
 LOG  ["uuid", "createdAt", "updatedAt", "expirationDate", "name", "device", "messages"]
 LOG  current sessions:
 LOG  new session: uuid,createdAt,updatedAt,expirationDate,name,device,messages
 LOG  current sessions after handle: 0
 LOG  event
 LOG  private message
 LOG  a0d35995-8d79-433a-aab9-1d911d20e756 []
 LOG  [TypeError: undefined is not an object (evaluating 'session.messages')]
 LOG  private message
 LOG  a0d35995-8d79-433a-aab9-1d911d20e756 ["0"]
 LOG  current sessions after handle: 0

as you can see the useEffect loads twice I don’t know why then i trigger new session and then session set to the state then I try to send message from the sender you notice that the session.messages is undefined then it finds the session
I don’t know why does it stack like this
thanks

Why I can’t acces this property in my class

I am trying to use this class to play and pause an interval timer but I am having problems with pause(). I don’t know why I can’t acces the timerId property from pause()

this.timerId return undefined in pause() . What am I doing wrong?

class IntervalTimer {
  callbackStartTime;
  remaining = 0;
  paused = false;
  timerId = null;
  _callback;
  _delay;

  constructor(callback, delay) {
    this._callback = callback;
    this._delay = delay;
  }

  pause() {
    console.log("this.timerId", this.timerId); //return undefined
    if (!this.paused) {
      this.clear();
      this.remaining = new Date().getTime() - this.callbackStartTime;
      this.paused = true;
    }
  }

  resume() {
    if (this.paused) {
      if (this.remaining) {
        setTimeout(() => {
          this.run();
          this.paused = false;
          this.start();
        }, this.remaining);
      } else {
        this.paused = false;
        this.start();
      }
    }
  }

  clear() {
    clearInterval(this.timerId);
  }

  start() {
    console.log("this.timerId", this.timerId); // return timerId correctly
    this.clear();
    this.timerId = setInterval(() => {
      this.run();
    }, this._delay);
  }

  run() {
    this.callbackStartTime = new Date().getTime();
    this._callback();
  }
}

export default IntervalTimer;

Chrome Browser is not opening in puppeteer

This is my full code, I have tried headless: false command and npm I puppeteer

const puppeteer = require('puppeteer');

(async () => {
const browser = await puppeteer.launch({headless:false});
const page = await browser.newPage()
const navigationPromise = page.waitForNavigation()

await navigationPromise

await page.goto('https://www.google.com/search?q=perfmatters+vs+wp+rocket&oq=perfmatters+vs+wp+rocket&aqs=chrome..69i57j69i64.3689j0j15&sourceid=chrome&ie=UTF-8')

await page.setViewport({ width: 1366, height: 657 })

await page.waitForSelector('.MjjYud:nth-child(6) > .g > .kvH3mc > .Z26q7c > .yuRUbf > a > .LC20lb')
await page.click('.MjjYud:nth-child(6) > .g > .kvH3mc > .Z26q7c > .yuRUbf > a > .LC20lb')

await browser.close()
})

Code Result:
This is result of my code nothing happen

Close menù when I click on navlink

I have this problem. When I click on menù link, the page scroll but the menù remain open. This is my code-pen link (For some reason, codepen don’t read che css color link, but don’t worry about it)
Js suggestions? I have just tried with on click function, but don’t work.

Thank you every body can help me!

[Link Codepen][MyCodepen]

.nav-link{
    font-weight: 300;
}
.text-menu{
    font-weight: 200;
}
.navbar-toggler{
    border: none;
}

.offcanvas-header{
    background-color: #0c0c0c;
    padding-left: 2.5rem;
    color: #eab736;
    
}
.offcanvas-body{
    background-color: #0c0c0c;
}
.nav-link{
    font-size: 1.3rem;
    color: white;
    padding-left: 2rem;
}
.nav-link:hover{
    font-size: 1.3rem;
    color: rgba(255, 255, 255, 0.20);
    padding-left: 2rem;
}
.text-menu{
    font-size: 0.7rem;
    color: rgba(255, 255, 255, 0.20);
    padding-left: 2rem;
}
.icon-white{
    color: white;
    font-size: 2rem;
}
.header-nav__social {
    padding-top: 3rem;
    list-style: none;
    display: inline-block;
    margin: 0;
    font-size: 1.2rem;
}

.header-nav__social li {
    margin-right: 12px;
    padding-left: 0;
    display: inline-block;
}

.header-nav__social li a {
    color: rgba(255, 255, 255, 0.20);
}

.header-nav__social li a:hover,
.header-nav__social li a:focus {
    color: white;
    transition: all 0.5s;
}

.header-nav__social li:last-child {
    margin: 0;
}
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>Example</title>


    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">

    <link href="https://getbootstrap.com/docs/5.2/assets/css/docs.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/font/bootstrap-icons.css">
</head>

<body>
<nav class="navbar fixed-top" id="mainNav">
  <div class="container-fluid">
    <a class="navbar-brand text-black js-scroll-trigger" href="#home">Brand name</a>
    <button class="navbar-toggler" type="button" data-bs-toggle="offcanvas" data-bs-target="#offcanvasNavbar" aria-controls="offcanvasNavbar">
      <i class="bi bi-list icon-black"></i>
    </button>
    <div class="offcanvas offcanvas-end" tabindex="-1" id="offcanvasNavbar" aria-labelledby="offcanvasNavbarLabel">
      <div class="offcanvas-header">
        <p class="offcanvas-title" id="offcanvasNavbarLabel">Menù</p>
        <button type="button" class="btn-close btn-close-white"  data-bs-dismiss="offcanvas" aria-label="Close" ></button>
      </div>
      <div class="offcanvas-body">
        
        <ul class="navbar-nav justify-content-end flex-grow-1 pe-3 text-white">
          <li class="nav-item">
            <a class="nav-link js-scroll-trigger" href="#home">Home</a>
          </li>
          <li class="nav-item">
            <a class="nav-link js-scroll-trigger" href="#about">About</a>
          </li>
          <li class="nav-item">
            <a class="nav-link js-scroll-trigger"  href="#works">Gallery</a>
          </li>
          <li class="nav-item">
            <a class="nav-link js-scroll-trigger" href="#contacts">Contacts</a>
          </li>
            
            <p class="text-menu mt-5">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quam minima beatae, repudiandae voluptatibus in suscipit dicta, facere consequuntur.</p>
            
 
        </ul>
    
           <ul class="header-nav__social">
                    <li>
                        <a href="#"><i class="bi bi-facebook"></i></a>
                    </li>
                    <li>
                        <a href="#"><i class="bi bi-twitter"></i></a>
                    </li>
                    <li>
                        <a href="#"><i class="bi bi-instagram"></i></a>
                    </li>
                    <li>
                        <a href="#"><i class="bi bi-behance"></i></a>
                    </li>
                </ul>
      </div>
    </div>
  </div>
</nav>
  
  
      <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-easing/1.4.1/jquery.easing.min.js"></script> 
  </body>
</html>

]1

Redirecting a user after submitting an embedded Google Form

I am tring to create a simple function with Google Apps Script that should redirect a user after submitting a form. The form is embedded in my webpage using an iframe. The function can be easily be triggered by the form-submit event, and is currently firing. However, I do get an error because “window is not defined”. I am completely new to Google Apps Scripts and I cannot find a solid reference on how to redirect to a specific link.

This is the function:

function form_submit_redirect() {
  window.location.href = "/users/";
}

This is the error:

Error ReferenceError: window is not defined
at form_submit_redirect(Code:2:3)

Events are behaving differently after updating to React 18

My menu stopped working after I updated to React 18. I am not in strict mode.

I do not understand how my code is now working. The code below used to work as I expected. But now I observed a “strange” effect.

Clicking on the menu icon will correctly “turn on” the menu box. What is bizarre is that when the menu box is turned on, it sets up and event handler to detect clicks on the document.body.

It then detects a second click on the document.body (there is only one click), closing the menu, so in effect you never see the menu. That is, it is now broken.

Timing has changed. Why?

export default () => {
  const dispatch = useDispatch();
  const menu = useSelector((state)=>state.MenuPage.on);
  function clicked() {
    console.log('DEBUG: Menu.jsx clicked')
    dispatch({type: 'toggleMenuPage'});
  }
  return (
    <div id="menu_hold">
      <SVGMenu onClick={clicked} id='menu_top'/>
      {menu && <MenuBox/>}
    </div>
  );
};

Here is the document.body handler in MenuBox.

  useEffect(() => {

    console.log('DEBUG: MenuBox.jsx useEffect()')

    function bodyClicked() {
      dispatch({type: 'toggleMenuPageOff'});
    }

    document.body.addEventListener('click', bodyClicked);

    return () => {
      document.body.removeEventListener('click', bodyClicked);
    };
  });

Filtering ag-grid cell value based on another cell value

I have a situation where I have two columns in ag-grid (types and subtypes). While edititing a specific row , I want when a user select a type(from dropdown on types cell click event ), my subtypes got filter , so that when I try to select subtypes from dropdown , I could only see subtypes related to that selected types only.
I have written a filterSubtype function which will do the filtering.

const filteringSubtypes = (params: ValueGetterParams, transactionSubTypes: TransactionSubType[]) : TransactionSubType[]=>{
  return transactionSubTypes.filter(subType => subType.transactionType.code === params.data.transactionType)
 }

I try to use first parameter as valueGetterParams so that I can get the value from subtype column,
Now I’m getting stuck that how can i use this function to get the desired result

Pasting my column definition also , to get better idea :-

  1. dropdown function to select data from a dropdown
const getRichEditableDropdownColumn = (
  values: any[],
  formatValue: (value: any) => any,
  valueSetter?: (params: ValueSetterParams) => boolean
): ColDef => {
  return {
    editable: isEditable,
    singleClickEdit: true,
    cellEditor: "agRichSelectCellEditor",
    cellEditorPopup: true,
    cellEditorParams: {
      values,
      formatValue,
    },
    valueSetter,
  };
  1. Subtype col definitiopn
{
      headerName: "Sub Type",
      field: "subType",
      ...getRichEditableDropdownColumn(
        filteringSubtypes(,subTypes), /// stuck here how to call filterSubtype method
        (subType: TransactionSubType) => subType?.name ?? subType,
        (params: any) => {
          const newValue = params.newValue;
          if (newValue) {
            params.data.subType = newValue.code;
            return true;
          }
          return false;
        }
      ),
    },
  1. Type col definition
{
      headerName: "Transaction Type",
      field: "type",
      ...getRichEditableDropdownColumn(
        types,
        (type: TransactionType) => type?.name ?? type,
(params: any) => {
          const newValue = params.newValue;
          if (newValue) {
            params.data.subType = newValue.code;
            return true;
          }
          return false;
        }
}

Calling class prototype methods via index with TypeScript

I would like to be able to call class prototype methods using bracket notation, so that the method name can be decided at run time:

classInstance['methodName'](arg);

I am failing to do this properly with TypeScript:

class Foo {
  readonly ro: string = '';
  constructor() {}
  fn(s: number) { console.log(s); }
}

const foo = new Foo();
const methods = ['fn'];

foo['fn'](0)

// Element implicitly has an 'any' type because expression of type 'string' can't be used to index type 'Foo'.
// No index signature with a parameter of type 'string' was found on type 'Foo'.
foo[methods[0]](1);

// This expression is not callable.
// Not all constituents of type 'string | ((s: number) => void)' are callable.
// Type 'string' has no call signatures.
foo[methods[0] as keyof Foo](1);

The above example is in the TS Playground.

I think that I have a reasonable understanding of what the errors mean and why the string literal in foo['fn'](0) does not produce an error. However, I don’t understand how to prevent the errors. I thought that I might be able to use Extract to build a type comprising of Function, but I’ve failed to do that.

How can I produce a list of typed method names over which my code can iterate? And better, is it possible for the class to export such a list so that users of the class can easily access them?

Background Information

I have a Playwright test that needs to iterate over a list of methods from a Page Object Model, producing a screenshot for each.

How can i prevent re-render of react component in useEffect?

enter image description here[enter image description here](https://i.stack.imgur.com/807xf.png)

I created a function thats fetch to my localhost inside useEffect, and inside of the useEffect I did a placement for the State with his setState,
the setFunc in this case takes the value for the ChartJS data.

Im trying to use ChartJS with data from my database.
if the dependencies on useEffect is empty, the data in the chart is undefined but if i have the state on the dependencies so the component re-render evry time.