Axios Promise.allSettled doesn’t work in parallel in Chrome

I have this parallel request mechanism in a ReactJS project. I followed the online sources while implementing this. I gather the promises in an array than feed it to allSettled then collect the result.

let promises = [];

for (const [_, url] of urls) {
    promises.push(axios.get(`https://url`, {
        timeout: 5000,
        signal: AbortSignal.timeout(5000), //Aborts request after 5 seconds
    }));
}

const result = await Promise.allSettled(promises)

My problem is that, in firefox this executes perfectly. However in Chrome, all the requests happen one by one(not parallel), so it is very slow and eventually timeout because of the 5 second limit I’ve put in.

Another interesting this is, if I open network tab and select “disable cache”, in Chrome, there requests happen in parallel and work the way they are supposed to.

What could be the reason for this?

axios version: 1.4.0

Node version: 18.2

How can I not have the addEventListener() functions run automatically when I run the project? [duplicate]

I have a small project I run using Live Server on VSCode. In this project I enter an email and password into fields. When I press save I want to store the values into localStorage, and clear the localStorage when I press clear.
But it seems that the addEventListener() runs automatically.

How do I get it to where the functions only run when I press the Save and Clear buttons?

Javascript

var email = document.getElementById('email');
var password = document.getElementById('password');

function save(email, password){
  try{
    localStorage.setItem("email", JSON.stringify(email) )
    localStorage.setItem("password", JSON.stringify(password) )
  }
  catch (err){
    console.log(err)
  }
  console.log(localStorage.getItem("email"));
  console.log(localStorage.getItem("password"));
}

function cancel(){
  localStorage.clear()
  console.log("Cancel Clicked")
}

document.getElementById("savebutton").addEventListener('click', save(email, password));
document.getElementById("cancelbutton").addEventListener('click',cancel());

HTML

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <link rel="stylesheet" href="style.css">
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Local Storage App</title>
  </head>
  <body>
    <div>
      <h2>Local Storage Practice Example</h2>
      <div id="inputs">
        <div id="inputflex">
          <label>Email</label>
          <input type="email" id="email" />
        </div>
        <div id="inputflex">
          <label>Password</label>
          <input type="password" id="password" />
        </div>
      </div>
      <div>
        <button id="savebutton">Save</button>
        <button id="cancelbutton">Clear</button>
      </div>
    </div>
    <script src="/main.js"></script>
  </body>
</html>

Image of project.
The bottom shows the logs. It runs each time I start the project or refresh. I want the code to run only when I click save or clear buttons.

How do i edit the codepen FlipDown.js Countdown?

I found this countdown clock in CodePen, but I need to edit it, I need to set the final date to May 30, 2024. ¿Does anybody know how to set up the final date?

document.addEventListener('DOMContentLoaded', () => {

  // Unix timestamp (in seconds) to count down to
  var twoDaysFromNow = (new Date().getTime() / 1000) + (86400 * 2) + 1;

  // Set up FlipDown
  var flipdown = new FlipDown(twoDaysFromNow)

    // Start the countdown
    .start()

    // Do something when the countdown ends
    .ifEnded(() => {
      console.log('The countdown has ended!');
    });

  // Toggle theme
  var interval = setInterval(() => {
    let body = document.body;
    body.classList.toggle('light-theme');
    body.querySelector('#flipdown').classList.toggle('flipdown__theme-dark');
    body.querySelector('#flipdown').classList.toggle('flipdown__theme-light');
  }, 5000);
  
  var ver = document.getElementById('ver');
  ver.innerHTML = flipdown.version;
});

Or anybody can tell me where ¿I can find a flip countdown easy to set up?

THANKS

Why is encodeURI() replacing { with a load of UTF8? [closed]

I am trying to encode a string like BNg{​​L3 using encodeURI() but the result I get is this:

BNg%7B%E2%80%8B%E2%80%8BL3

Of course, I would like BNg%7BL3

I found that the sequence %E2%80%8B is ZERO WIDTH SPACE but it’s not in the provided string (I get the string from a query’s body, this problem shows up server-side). What does cause this behaviour? And more importantly, how do I get what I want?

Play only one audio at once

I have aa list of podcast links using the audio tag, they all play when I click on the play button but i want the first to pause when i play another

<div class="podcast-container">
    <audio controls src="https://assets.mixkit.co/music/preview/mixkit-tech-house-vibes-130.mp3"></audio>
    <audio controls src="https://assets.mixkit.co/music/preview/mixkit-hazy-after-hours-132.mp3"></audio>
    <audio controls src="https://assets.mixkit.co/music/preview/mixkit-tech-house-vibes-130.mp3"></audio>
</div>

I tried the below code to pause the audio but then it doesn’t play at all. Please help

  const tracks = Array.from(document.querySelectorAll('audio'));
   tracks.forEach(function (track) {
      track.addEventListener('play', (event) => {
         tracks.forEach(function (track) {
             track.pause();
         })
      })
   })

Is there a way to catch SyntaxError[s] thrown by the browser?

I have an angular app that introduced a negative lookbehind regex and broke compatabiliity with safari 15.6. We want to still support that version and have reverted to using compatible regex that it likes however this question is more about the code that throws the SyntaxError and how if possible can the I catch the error and then handle appropriately instead of serving the white screen of death.

Known things;

  • Non V8 browsers such as Safari don’t support them (lookbehind regex)
  • The immediate fix is to downgrade to tolerable regex syntax
  • I’ve successfully created the script tags in vanillaJS such that I could attach eventHandlers to each script. However the SyntaxError being thrown doesn’t trigger the errorHandler.0_o

Primary question:

  • Is the SyntaxError thrown by safari 15.6 in this case catchable? If so from where?
  • What code is parsing the regex and throwing an error if its not supported?

How to aggregate JSON data as expected?

I have response text from API as below, I want aggreate them to new format response. But it is quite difficult, please help me (using Javascript)

Response from API:

[
  {
    sumTime: "2024-04-25 12:00:00",
    equipParaName: "P1",
    sumValue: 5
  },
  {
    sumTime: "2024-04-25 05:00:00",
    equipParaName: "P2",
    sumValue: 10,
  },
  {
    sumTime: "2024-04-25 09:00:00",
    equipParaName: "P1",
    sumValue: 8
  },
  {
    sumTime: "2024-04-25 08:00:00",
    equipParaName: "P2",
    sumValue: 3,
  },
  {
    sumTime: "2024-04-25 08:00:00",
    equipParaName: "P3",
    sumValue: 12,
  }
]

Conditions:

  • With same sumTime, the equipParaName can not be duplicated

  • If have 3 unique equipParaName, the expecting result has maximum 3 attributes belongs to them in one object

  • Same equipParaName in result list must order by sumTime ASC

    equipParaName: P1, sumTime: 2024-04-25 12:00:00, sumValue: 5
    
    equipParaName: P1, sumTime: 2024-04-25 09:00:00, sumValue: 8
    
    ==> The sumTime 2024-04-25 09:00:00 should be added to 1st object and sumTime: 2024-04-25 12:00:00 added to 2nd object in result list
    

Expect:

[
  {
    index: 1,
    P1: 8,
    P1_sumTime: "2024-04-25 09:00:00",
    P2: 10,
    P2_sumTime: "2024-04-25 05:00:00",
    P3: 12,
    P3_sumTime: "2024-04-25 07:00:00"
  },
  {
    index: 2,
    P1: 5,
    P1_sumTime: "2024-04-25 12:00:00",
    P2: 3,
    P2_sumTime: "2024-04-25 08:00:00"
  }
]

How to wrap if condition in then function in javascript?

i am new to learning javascript. i am currently trying to wrap if condition inside a then function.

below is my code,

const createType = ({
    firstTypes = [],
    secondTypes = [],
    ...allType
    } = {}, skip = true) => {
    const builtType = buildType(allType);
    let finalType;
    let finalSecondTypes;

    return apiPostType(builtType)
    .then(waitForSync(cy.apiGetTypeWithRetry))
    .then(createdType => {
    finalType = keysToCamelCase(createdType);
    const firstTypesToCreate = firstTypes.map(
        firstType => () =>
        cy.createFirstType({
            ...firstType,
            allType: createdType.id,
        })
    );

the above code works fine. now i want to execute waitForSync(apiGetTypeWithRetry) only if skip is set to false. hence i tried like below,

const createType = ({
    firstTypes = [],
    secondTypes = [],
    ...allType
    } = {}, skip = true) => {
    const builtType = buildType(allType);
    let finalType;
    let finalSecondTypes;

    return apiPostType(builtType)
    .then(createdType => {
        if(skip = false) {
            waitForSync(cy.apiGetTypeWithRetry);
        }
    })
    .then(createdType => { //here createdType is undefined
    finalType = keysToCamelCase(createdType);
    const firstTypesToCreate = firstTypes.map(
        firstType => () =>
        cy.createFirstType({
            ...firstType,
            allType: createdType.id,
        })
    );

but after adding if condition in the .then() function the createdType for the next .then() function is undefined. i am not sure how to pass the promise from the previous .then function.

could someone help me with this. thanks.

How can I get the website URL using Voiceflow Chatbot?

I’m trying to add a feature to my Voiceflow chatbot where I can save as a variable the website URL. I need it for the chatbot flow so it should be saved as a variable inside the flow.

I tried using the javascript module:

websiteURL = window.location.href

It says that window is not defined.

I also asked to the AI Voiceflow Assistant an it told me to modify the launching code to get the url as a variable, it didn’t work neither.

<script type="text/javascript">
  (function(d, t) {
      var v = d.createElement(t), s = d.getElementsByTagName(t)[0];
      v.onload = function() {
        window.voiceflow.chat.load({
          verify: { projectID: 'XXXXCURRENT_IDXXXX' },
          url: 'https://general-runtime.voiceflow.com',
          versionID: 'production',
          variables: {
            websiteURL: window.location.href
          }
        }).then(() => {
          setTimeout(function() {
                  window.voiceflow.chat.open();
                }, 200);
        });
      }
      v.src = "https://cdn.voiceflow.com/widget/bundle.mjs"; v.type = "text/javascript"; s.parentNode.insertBefore(v, s);
  })(document, 'script');
  </script>```


behaviour of setTimeout() in keeping track of variables? [closed]

I was coding recently and was stuck scratching my head over why, even when I pass the string that is initialised already, as a parameter, the setTimeout’s callback function still prints it as undefined.
Does it not keep track of the variable it needs later?

This is the simple illustration:

console.log("lets start");
const str="123";
setTimeout((str)=>console.log(str),5000);

so should i never pass an argument in setTimeout?

First class functions with callback

I am learning about functional programming, and have a question at this example in the book Mostly Adequate Guide:

// this line
ajaxCall(json => callback(json));

// is the same as this line
ajaxCall(callback);

From what I see, ajaxCall takes json as argument. But, callback is not a JSON. Part of the confusion is that I do not know what ajaxCall is – is it a generic placeholder here, or a established function in the wild?

How are the above two lines equivalent?

Match a Regex Pattern that doesn’t follow the serial arrangement in the pattern

How do i match a string to a regex pattern in javascript, but the string does not have to follow the serial arrangement in the regex Pattern.
The regex pattern test against a string containing brackets with the conditions that;

  • Open brackets must be closed by the same type of brackets.
  • Open brackets must be closed in the correct order.
  • Every close bracket has a corresponding open bracket of the same type.

This is what i tried;

const pattern = /^(())*({})*([])*$/

if i test it against these strings, it works fine

console.log(pattern.test("(){}[]")) //returns true
console.log(pattern.test("(]") //returns false

but if change the order the brackets appear in the regex then i get false

console.log(pattern.test("{}()[]") // returns false

I want the string of brackets to match the pattern no matter which brackets comes first or second as long as they meet the above conditions

Getting the error ” Should have a queue” when using React-Query mutation

I’m trying to figured out how to implement react-query in my react-native app. I’m executing a simple firebase login function from react-query mutation. Then in my signIn component I will call the mutation from a submit button. When I thought it was this simple, I’m keep getting “Error: Should have a queue. This is likely a bug in React. Please file an issue.” However, the code was able to reach the success part of the mutation. Any helps on this would be appreciated as there are only few guidances online that showcase the implementation of react-query with firebase.

These are the full errors:

Running "App" with {"rootTag":231,"initialProps":{}}
 ERROR  Warning: React has detected a change in the order of Hooks called by SignIn. This will lead to bugs and errors if not fixed. For more information, read the Rules of Hooks: https://react.dev/link/rules-of-hooks

   Previous render            Next render
   ------------------------------------------------------
1. useRef                     useRef
2. useState                   useRef
   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

    in SignIn (created by SignMain)
    in RCTView (created by View)
    in View (created by AnimatedComponent(View))
    in AnimatedComponent(View)
    in Unknown (created by SignMain)
    in RCTView (created by View)
    in View (created by AnimatedComponent(View))
    in AnimatedComponent(View)
    in Unknown (created by SignMain)
    in RCTView (created by View)
    in View (created by SignMain)
    in RCTView (created by View)
    in View (created by KeyboardAvoidingView)
    in RCTView (created by View)
    in View (created by KeyboardAvoidingView)
    in KeyboardAvoidingView (created by SignMain)
    in RCTScrollContentView (created by ScrollView)
    in RCTScrollView (created by ScrollView)
    in ScrollView (created by ScrollView)
    in ScrollView (created by SignMain)
    in SignMain (created by AuthNavigation)
    in AuthNavigation (created by App)
    in EnsureSingleNavigator
    in BaseNavigationContainer
    in ThemeProvider
    in NavigationContainerInner (created by App)
    in WithSplashScreen (created by App)
    in App (created by AppWrapper)
    in QueryClientProvider (created by AppWrapper)
    in AppWrapper
    in RCTView (created by View)
    in View (created by AppContainer)
    in RCTView (created by View)
    in View (created by AppContainer)
    in AppContainer
    in App(RootComponent)
 ERROR  Error: Should have a queue. This is likely a bug in React. Please file an issue.

This error is located at:
    in SignIn (created by SignMain)
    in RCTView (created by View)
    in View (created by AnimatedComponent(View))
    in AnimatedComponent(View)
    in Unknown (created by SignMain)
    in RCTView (created by View)
    in View (created by AnimatedComponent(View))
    in AnimatedComponent(View)
    in Unknown (created by SignMain)
    in RCTView (created by View)
    in View (created by SignMain)
    in RCTView (created by View)
    in View (created by KeyboardAvoidingView)
    in RCTView (created by View)
    in View (created by KeyboardAvoidingView)
    in KeyboardAvoidingView (created by SignMain)
    in RCTScrollContentView (created by ScrollView)
    in RCTScrollView (created by ScrollView)
    in ScrollView (created by ScrollView)
    in ScrollView (created by SignMain)
    in SignMain (created by AuthNavigation)
    in AuthNavigation (created by App)
    in EnsureSingleNavigator
    in BaseNavigationContainer
    in ThemeProvider
    in NavigationContainerInner (created by App)
    in WithSplashScreen (created by App)
    in App (created by AppWrapper)
    in QueryClientProvider (created by AppWrapper)
    in AppWrapper
    in RCTView (created by View)
    in View (created by AppContainer)
    in RCTView (created by View)
    in View (created by AppContainer)
    in AppContainer
    in App(RootComponent), js engine: hermes

signIn.tsx

function SignIn() {

  const signInMutation = authAPI_login;
  const validationSchema = loginValidation;

  type SignInFormSchema = z.infer<typeof validationSchema>;

  const {control, handleSubmit, setFocus} = useForm<SignInFormSchema>({
    defaultValues: loginFormData,
    resolver: zodResolver(validationSchema),
  });

  const onSubmit = async (data: any) => {
     signInMutation.mutate({
          email: data.email,
          password: data.password,
        });
  };

  return (
    <View style={styles.rootContainer}>
      <View style={styles.inputContainer}>
        <TxtInput
          height={40}
          width={300}
          control={control}
          name="email"
          placeholder="Email"
          inputMode="email"
          nextFocus={true}
          isLoading={false}
          secureTextEntry={false}
          setNextFocus={() => {
            setFocus('password');
          }}
        />
      </View>
      <View style={styles.inputContainer}>
        <TxtInput
          height={40}
          width={300}
          control={control}
          name="password"
          placeholder="Password"
          inputMode="text"
          isLoading={false}
          secureTextEntry={true}
        />
      </View>
        <Button
          height={40}
          width={300}
          outline={true}
          isListening={true}
          isLoading={false}
          // onPress={handleSubmit(onSubmit)}
          onPress={() => {return onSubmit('test') }}
          >
          Sign In
        </Button>
     
    </View>
  );
}

api.tsx

export async function authSV_login(email: string, password: string) {
  return auth()
    .signInWithEmailAndPassword(email, password)
    .then((auth) => {
      return true
    })
    .catch(error => {
      if (error.code === 'auth/email-already-in-use') {
        console.log('That email address is already in use!');
      }

      if (error.code === 'auth/invalid-email') {
        console.log('That email address is invalid!');
      }

      return false
    });
}

export const authAPI_login = useMutation({
    mutationFn: ({ email, password }: {email: string, password: string}) => authSV_login(email, password),
    onSuccess: async (data) => {
      console.log('success', data);
    },
    onError: async (error) => {
      console.log('error', error);
    },
})