Correctly delaying setTimeout

In the following function

function test1(n, delay) {
  for (let i = 0; i < n; i++) {
    setTimeout(() => {
      console.log(i)      
    }, delay)    
  }  
}

test1(3, 1000)

After 1 second, I immediately console.log 1, 2, and 3 simultaneously.

If I multiply delay by i,

function test1(n, delay) {
  for (let i = 0; i < n; i++) {
    setTimeout(() => {
      console.log(i)      
    }, i * delay)    
  }  
}

test1(3, 1000)

I console.log every i in my loop after 1 second. Why does this work?

Also, why does the code below

function test2(n, delay) {
  let promise = new Promise(resolve => setTimeout(() => {
    resolve()    
  }, delay))
  for (let i = 0; i < n; i++) {
    promise.then(console.log(i))  
  }  
}

test2(3, 1000)

immediately console.log 1, 2, and 3 simultaneously instead of waiting every second to console.log the next i value? Is there a way to console.log the next i value after waiting every second without using async and await?

How to load two external files in D3.js version 7?

To load one TopoJson file in D3 version 7 is simple as:

d3.json("file01.json").then(function(topology) {

To load two files in previous versions you could use for example in version 6:

Promise.all([
    d3.json("file01.json"),
    d3.json("file02.json", function(d) {
        data.set(d.code, +d.pop)
    })
]).then(function(loadData){

and in version 4, for example:

d3.queue()
  .defer(d3.json, "file01.json")
  .defer(d3.json, "file02.json", function(d) { data.set(d.code, +d.pop); })
  .await(ready);

I tried both in version 7 and received the notice that promisse or queue are not a function. So I interpreted that in version 7 there’s another way to load two external files.

Thanks for any help which I couldn’t find until now, despite searching all over the in Internet. There’s a lot of material about version 3 to 6, but much less to version 7.

Count the number of values

Here is a task to count the number of true in each age:

users = {
 // ...
 age = x; // random number
 sport_life true; // or false
 // ...
}

And display it in a chart (chart.js). Here is how to update.
I don’t know how to put it all together. Thanks in advance!

Google Sheets: How do I list rows of data copied from another sheet consecutively, in order, and without overwriting current data through scripting?

I’m kind of new to working with Google Sheets, and I’ve stumbled across an issue while creating buttons for a ticket system. I’ve been having trouble getting the copied data to just fill the other sheet from the second row and down without gaps or overwriting existing data.

The script basically checks if a checkbox of a certain row is ticked, copies the data in that row, moves that data to another sheet, and then resets that row to it’s original state. Meaning it doesn’t completely delete the row or format, but only copies the contents.

Here’s the code I’ve been working with so far:

function MigrateInProgress() {
    var ss = SpreadsheetApp.getActiveSpreadsheet();  
    var s = ss.getSheetByName('Copy of New Tickets');
    var s2 = ss.getSheetByName('In Progress');
    var r = s.getRange('G:G');    
    var v = r.getValues();  
    var dataset = [];
for(var i=v.length-1;i>=0;i--) 
    if(v[0,i]=='true') { 
        var data = s.getRange(i+1,1,1,6).getValues(); 
        s2.getRange(i+1,s2.getLastColumn()-6,data.length,6).setValues(data); 
        var datasetrange = s.getRange(i+1,1,1,6);
        datasetrange.clear({contentsOnly: true});
        datasetrange.clear({formatOnly: false});
        s.getRange(i+1,7).setValue(false);    
  }
}

Here’s some screenshots to help contextualize what I mean:

Screenshot 1

Screenshot 2

Screenshot 3

Any help would be greatly appreciated. Thank you!

Mobile browser positions elements as if the view is 360px wide, but renders images on the page at a higher resolution. How does this work?

I was having a hard time figuring out how to phrase this. Sorry if this is a noob question, I’m new to responsive design and mobile web design in general.

My phone (Galaxy s10e) will render my webpage as if it’s 360 pixels wide, with all elements positioned appropriately based on this width. I have several image tags on the site that are the same width. I was using src images that are 360px wide, and this looks fine on desktop because it is actually rendering my images at 360px, but on mobile the images alone appear to be rendering at a much higher resolution, causing it to look terrible due to upscaling.

If someone could explain to me what is happening here it would really help, since I can’t find information on this specific behavior. Some questions I have:

  • Is the browser choosing to position the elements based on a 360px width while rendering the actual content at the screen’s resolution?
  • How do I account for this in my design? I considered rendering the images at the higher resolution and then having the page dynamically scale those images down (so even though the actual div is 360px, the browser can use the ‘extra space’ allotted by max-width to render the image at a higher resolution), but I want the images to remain 360px wide on desktop, not the higher max-width for mobile rendering.
  • Where can I learn all about this behavior so I know how to tackle responsive image scaling in the future?

Thank you for your time. Let me know if you have any other questions. I’m using ReactJS to develop the site.

Need help transforming GraphQL results

A returned schema looks like the following:

{
    data: {
        posts: {
            edges: [
                {
                    post: {
                        id: ‘1’,
                        title: ‘Foo’
                    },
                    post: {
                        id: ‘2’,
                        title: ‘Bar’
                    }
                }
            ]
        }
    }
}

This works and I can use it, but I’m having to create nested interfaces unfortunately.

Question: Can I either simplify the returned results OR transform them with JavaScript map()?

Ideally, I’d like for the GQL response (or resulting object) to be like:

{
    data: {
        posts: [
            post: {
                id: ‘1’,
                title: ‘Foo’
            },
            post: {
                id: ‘2’,
                title: ‘Bar’
            }
        ]
    }
}

Note: I do not have the ability to update the server-side GraphQL schema. The solution must be client/consumer side.

Thanks!

Merge two array of objects not based on key

I want to marge two arrays not based on key

Array1

[
  { size: "45", color: "red" }, 
  { size: "48", color: "blue" }
]

Array2

[
  { designation: "short", price: "540" }, 
  { designation: "jeans", price: "600" }
]

I need to merge these two arrays and expected this array

[
  { size: "45", color: "red", designation: "short" }, 
  { size: "48", color: "blue", designation: "jeans" }
]

How can do it?

Problem, react-lazyload render all components at once

Hi I’m using Marvel API and I have this:

export default function App() {
  const [characters, setCharacters] = React.useState([]);
  
  const items = characters.map((character, idx) => (
    <LazyLoad key={idx} once throttle={2000} height={"300"}>
      <Character
        img={
          character.thumbnail.path +
          "/standard_xlarge." +
          character.thumbnail.extension
        }
        name={character.name}
      />
    </LazyLoad>
  ));

  React.useEffect(() => {
    fetch(
      "https://gateway.marvel.com/v1/public/characters?ts=1&apikey=e8aa37188987325dca0c570b01707e2c&hash=d784691874995aae3b9fb373b5a4d1da&limit=50"
    )
      .then((response) => response.json())
      .then((data) => setCharacters(data.data.results));
  }, []);

  React.useEffect(() => {
    forceCheck();
  });

  return (
    <div className="App">
      <h1>My Hero's</h1>
      <div>{characters.length ? items : null}</div>
    </div>
  );
}



function Character({ img, name }) {
  return (
    <div style={{ height: "300px", width: "200px", backgroundColor: "purple" }}>
      <h3>{name}</h3>
      <img height="200" width="200" src={img} />
    </div>
  );
}

My problem is that when the fetch loads all the data the lazyload components load all at once. Pls Help me. I’m using react-lazyload

My codesandbox

How to get the number of elements for elements that satisfy a condition

I’m having a problem. I have an array as shown below:

0: {type: 'Text', id_a: '123789', value: 'The fifth chapter of the World Première Ducati will be held at the Expo Dubai on December 9th.', number: 2, id: 7}
1: {type: 'Image', id_a: '123789', value: 'b_desertx-dwp2022-2-uc336332-high.jpg', number: 3, id: 8}
2: {type: 'Video youtube', id_a: '123789', value: 'https://youtu.be/SnuyDoXxC4g', number: 5, id: 10}
3: {type: 'Image', id_a: '123456', value: 'moto_guzzi_v100_mandello.jpg', number: 3, id: 3}
4: {type: 'Text', id_a: '123456', value: 'The star of the Piaggio group stand is without doubt ... Discover all his secrets with our video', number: 2, id: 2}

Of these I want, for example, to take those that have an id_a equal to 123456 and have me return the value (therefore, referring to id_a = 123456 it must return the two relative arrays) then

3: {type: 'Image', id_a: '123456', value: 'moto_guzzi_v100_mandello.jpg', number: 3, id: 3}
4: {type: 'Text', id_a: '123456', value: 'The star of the Piaggio group stand is without doubt ... Discover all his secrets with our video', number: 2, id: 2}

Except I get this below

{type: 'Image', id_a: '123456', value: 'moto_guzzi_v100_mandello.jpg', number: 3, id: 3}
{type: 'Text', id_a: '123456', value: 'The star of the Piaggio group stand is without doubt ... Discover all her secrets with our video', number: 2, id: 2}

without the numbering in order to be able to retrieve the value (therefore using the value attribute) of each of them.

How can I do this?

   var myArr = JSON.parse(this.responseText);
   for(var i = 0, len = myArr.Items.length; i < len; i++){           
        var id_art = myArr.Items[i].id_a;
        if(id_art == 123456) {
            myArr.Items[i];
            console.log(myArr.Items[i]);
   }

AntD+React: Browserslist config problem. I can’t customize the theme in Ant Design

I am trying to customize the theme in my very first draft of the AntD+React application. The steps I followed are from this official website. enter link description here

F:apppj1antd-demonode_modulesreact-scriptsscriptsstart.js:19


throw `enter code here`err;
  ^
Error [BrowserslistError]: Browserslist config should be a string or an array of strings with browser queries
    at check (F:apppj1antd-demonode_modulesbrowserslistnode.js:67:11)
    at parsePackage (F:apppj1antd-demonode_modulesbrowserslistnode.js:108:5)
    at F:apppj1antd-demonode_modulesbrowserslistnode.js:327:29
    at eachParent (F:apppj1antd-demonode_modulesbrowserslistnode.js:53:18)
    at Object.findConfig (F:apppj1antd-demonode_modulesbrowserslistnode.js:313:20)
    at Function.loadConfig (F:apppj1antd-demonode_modulesbrowserslistnode.js:232:37)
    at checkBrowsers (F:apppj1antd-demonode_modulesreact-dev-utilsbrowsersHelper.js:45:32)
    at Object.<anonymous> (F:apppj1antd-demonode_modulesreact-scriptsscriptsstart.js:78:1)
    at Module._compile (node:internal/modules/cjs/loader:1101:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10) {
  browserslist: true
}
error Command failed with exit code 1.

I don’t know how to deal with it. Can anyone help me out, please? Should I just simply change all the files below? If so, then how to change them.