How can i make this code run asynchronously

const delayFunction = async () => {
  const startTime = new Date().getTime();

  const duration = 10000; 

  console.log('START')
  while (new Date().getTime() - startTime < duration) {
   // this loop runs for 10 seconds
  }
  console.log('STOP');
};

const starterFunction = async () => {
  console.log('1');
  delayFunction();
  console.log('2');
  return 'DONE'
};

console.log(starterFunction())

so now I want an output as below:

1

2

DONE

START

STOP

If anyone knows how to achieve this with asynchronous programming please help me with this.

I tried creating a new promise and tried to execute the code inside it but even that dosent seem to be working.

const delayFunction = async () => {
  return new Promise((resolve,reject) => {
     const startTime = new Date().getTime();

     const duration = 10000; 

     console.log('START')
     while (new Date().getTime() - startTime < duration) {
     // this loop runs for 10 seconds
     }
     resolve(console.log('STOP'));
  });
};

getSelection().collapseToEnd() does not work

What I am trying to do is move the caret to the end of the string when the element is focused.

collapseToEnd() does not work. Instead, if you uncomment getSelection().collapseToEnd(), it seems to remove the selection altogether or favors the user selection.

Any help would be greatly appreciated.

const div = document.querySelector('div')

div.addEventListener('focus', moveCaretToEnd)

function moveCaretToEnd() {
  getSelection().setBaseAndExtent(
    div.childNodes[0], div.textContent.length,
    div.childNodes[0], div.textContent.length-1
  )
  // getSelection().collapseToEnd()
}
div {
  width: 500px;
  height: 150px;
  font-size:  3rem;
  background: skyblue;
}
<div contenteditable>This is a test</div>

I still need help on finishing my trench traversal program to pass all tests but am still at a standstill where it says a variable is not an iterable

This problem has still been nagging at me for weeks, and I’ve made no further progress. I’ve got previous code passing tests, and here’s that which is still giving me trouble.

// Function to traverse trenches
function trenchTraversal(node, matrix, visited) {

    // Get coordinates of node passed in
    const [row, col] = node;

    // Log visited set
    console.log(`Visited Set: ${visited}`);

    // If node depth less than -5, return false
    if (matrix[row][col] >= -5) return false;

    // Set stack equal to node passed in
    const stack = [node];

    // Add node passed in to visited set
    visited.add(node.toString());

    // Path array
    const pathArr = [];

    // While the stack has length
    while (stack.length) {

        // Get current node from stack
        const current = stack.pop();

        // Push current node to path array
        pathArr.push(current);

        // Set current coordinates to the current node
        const [currentRow, currentCol] = current;

        // Get current node value from matrix
        const currentNode = matrix[currentRow][currentCol];

        // Find neighbors of current node
        const neighbors = findNeighbors(current, matrix);

        const neighborCoords = [];

        neighbors.forEach(neighbor => {

            neighborCoords.push([neighbor[0], neighbor[1]].toString());

        });

        // Loop through neighbors
        neighborCoords.forEach(neighborCoord => {

            // If the visited note doesn't have neighbor coordinates
            if (!visited.has(neighborCoord)) {

                // Push the neighbor onto the stack
                stack.push(neighbors[neighborCoord]);

                // Add neighbor coordinates to visisted set
                visited.add(neighborCoord.toString());

            };

            // Check if trench is T-shaped
            if (visited.has(neighborCoord[0] - 1 && neighborCoord[1] - 1)) return false;

        });

        // If the path is three or more nodes long, return true
        if (pathArr.length >= 3) return true;

    };

    // Return false
    return false;

};

// Function to identify trenches
function identifyTrench(trenchMatrix) {

    // Create set to hold visited coordinates
    const visited = new Set();

    // Loop for rows
    for (let i = 0; i < trenchMatrix.length; i++) {

        // Inner loop for columns
        for (let j = 0; j < trenchMatrix[0].length; j++) {

            // If the coordinate is deeper than -5
            if (trenchMatrix[i][j] < -5) {

                // If a valid trench exists, return true
                if (trenchTraversal([i, j], trenchMatrix, visited)) return true;

                // Else return false
                else return false;

            };

        };

    };

    // Return false if no valid trenches are found
    return false;

};

And I get this error.

TypeError: current is not iterable

I remember not getting this error before when I was last working on the code. I would appreciate any help in getting this problem completely resolved.

Issue with user input received

code is here: https://github.com/bjcompto/Find-your-hat-game-/blob/main/main.js

const prompt = require('prompt-sync')({sigint: true});

const hat = '^';
const hole = 'O';
const fieldCharacter = '░';
const pathCharacter = '*';


class Field {
    constructor(gameField) {
        this.gameField = gameField; 
    }

    newGame() {
        console.log(this.gameField); 
    }
    
    printBoard() {
        setTimeout(() => {
            let twoArrToStr = this.gameField.map(arr => arr.join('')).join('');
            console.log(twoArrToStr); 
        }, 1500);
    }

    userDirections() {
        const userMove = prompt('Which direction would you like to move? ');
        //console.log(typeof userMove); 
        console.log(`You want to where again? n${userMove}  nLet me see if that's possible lol`); 
        this.userMovement(userMove);
        this.printBoard();
        this.holePresent();
    }

    holePresent() {
        for(let i = 0; i < this.gameField.length; i++) {
            for(let j = 0; j < this.gameField[i].length; j++) {
                if(this.gameField[i][j] === this.hole) {
                    console.log('There is a hole here.')
                    this.newGame();
                    break; 
                }
            }
        }
    }

   userMovement(str) {
        if(this.userMove === 'right') {
            //move right 1 space; 
        } else if(this.userMove === 'left') {
            //move left 1 space;
        } else if (this.userMove === 'up') {
            //move up 1 space;
        } else if(this.userMove === 'down') {
            //move down 1 space; 
        } else {
            console.log('invalid entry.  You can move right, left, up or down.  Enter valid entry')
            this.userDirections(); 
        }
    }

}



const gameOne = new Field([
    [pathCharacter, fieldCharacter, fieldCharacter],
    [fieldCharacter, hole, fieldCharacter],
    [fieldCharacter, hat, fieldCharacter]
])


gameOne.userDirections(); 

for convenience posted link for code on my github and actual code. I’m new so there will be noob stuff in my code. I’m having an issue with my userMovement method within the userDirection method. userMovement reads user input and performs an action based on the input. I thought I wrote it to only accept right, up, down, and left. however, it just rejects everything and gives my error message even for valid entries of right, left, up and down. Any guidance is appreciated

after running node in terminal(macOS) expected output of:

`You want to where again? n${userMove}  nLet me see if that's possible lol` 

followed by the following methods:

this.userMovement(userMove); 
this.printBoard();
this.holePresent(); 

actual output:

whether entry is valid. for ex: right, left, up or down.
Or invalid. for ex. around, under etc

I receive my error message:

console.log('invalid entry.  You can move right, left, up or down.  Enter valid entry')
            this.userDirections(); 

and then I just end up stuck in the program. side note how do I force stop the program in node. Tried process.exit() but it is just interpreted as an invalid move and the program continues

How can I copy formatted text using HTML and JavaScript?

I would like to implement a button on my webpage that allows users to copy formatted text to their clipboard. Shortcuts and context menus are disabled on my page, but I still want users to be able to copy formatted text, similar to using Ctrl + C. Can someone please point me in the right direction?

p.s. The execCommand() method is deprecated. so this will not be an answer.
p.s. i am looking for a method that does not use any external libraries.

i am a total beginner in js so any help will be appriciated

Can you inline a bundler compiled script with NextJS SSR?

In my NextJS app, I have the need for javascript to run as soon as the HTML markup is hydrated (specifically before the first contentful paint).

I know that I can inline a <script> tag like this and get my code to run as soon as the browser parses the DOM:

// In app.tsx

<div
  dangerouslySetInnerHTML={{
    __html: `<script type="text/javascript">console.log('hello');</script>`,
  }}
/>

Thats cute, but the actual code is a little more complex and would benefit from being separated into a few files.

Is there any way to define a separate entrypoint bundle to inline with NextJS? Or do I need to compile it myself and use a webpack replace plugin to swap it in after the build completes?


<div
  dangerouslySetInnerHTML={{
    __html: `<script type="text/javascript">__ENTRYPOINT_2_BUNDLE__</script>`,
  }}
/>

If I could make up my own API, it might look like this:

<Script type="inline-bundle" entrypoint="/bundles/ssr/index.js" />

How to calculate bubbles radiuses depends of data?

Have a question about cryptobubbles bubbles radiuses mathematics

Can somebody write a formula of dependences between percentage of coin and radius of babble?
this dependence is definitely not linear
But I can’t understand true dependence

Thanks!

I have linear formula
let d = (maxDiametr / 100 * (currentPercentage / (maxPercentage / 100)))

But want to understand hot to calculate some coefficient to make it work similar to cryptobubbles

Sanity error when trying to run vercel build: sanity/..page.jsx doesn’t have a root layout. To fix this error, make sure every page has a root layout

Running my project locally works totally fine but it does not when I am try to deploy it to vercel.

It says ⨯ sanity/[[…index]]/page.jsx doesn’t have a root layout. To fix this error, make sure every page has a root layout.
Compiler server unexpectedly exited with code: 1 and signal: null

I tried googling but found no solutions so I deleted the files by sending it to the trash bin but when I do that it is unable to fetch the data from the Sanity back-end. I don’t know what to do. Here is my code for the page.jsx:

'use client'

import { NextStudio } from 'next-sanity/studio'
import config from '../../../../sanity.config'

export default function StudioPage() {
  return <NextStudio config={config} />
}

Creating a loop that creates multiple divs with unique ids and names in JavaScript

I want to create multiple div html elemwnts in the dom that have unique ids and names – that is after each loop the name and id of the div element changes e.g first div will be div1 and id name will be divId1 while second will be div2 and id will be divId2;

let body = document.querySelector('body')
let num;
//num will be depend on users choice

for(i=0;i<num.length;i++){
  const div1 = document.createElement('div')
  div1.id = 'divId1'
  //the div styling comes here
  body.appendChild(div1)
  /*
  Next div shkuld have name of div2, id of divId2 and appended as div2
  */
}

This will Just create multiple HTML div elements with same ids.

Return value from JavaScript to AppleScript

I have exactly the same problem as in this question but I don’t know how to apply that solution to my situation. My JavaScript looks like this:

var result = [];
var xpathResult = document.evaluate('" & xpathExpression & "', document, null, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null);
var node;
while (node = xpathResult.iterateNext()) {
    result.push(node);
}
result;

and when I execute it in the browser console it returns a string (or null) but how do I get that string to be returned to my AppleScript?

I have an simpler version of the JavaScript

var result = document.evaluate(''" & xpathExpression & "', document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
result.singleNodeValue"

but it has the same problem – no return value. I can even do an alert() and the string is displayed in the browser but it seems impossible to get the string back to the AppleScript.

How to write to multiple Realtime Database Instances from a Cloud Function? [duplicate]

I have a firebase project up and running with a realtime database and cloud functions in javascript and everything is working well. I added another database instance to the project recently and I would like to be able to write data directly to that database, as well as the original database. Unfortunately I have only been able to write to the default/original database, no matter what I try.

Currently I can write to the first database (we’ll call it db1) using this method:

admin.database().ref().child("node_name_here").set("value_to_set")...

As you can see, I don’t need to specify the instance name, it just defaults to the original db1 database. I would like to be able to write to the second database instance within this same function too.
I did a lot of research but didn’t find anything that directly answered my question. I tried various solutions, such as passing in the instance name and also the instance link something like this.

admin.database().instance("db2").ref().child("node_name_here").set("value_to_set"){

And also something like this,

admin.database().instance("https:www.my_database_url.com/db2").ref().child("node_name_here").set("value_to_set")...

I have been able to listen to and write to the second database with database listener functions such as below,

exports.testFunction = functions.database.instance("db2").ref('/items/{pushId}').onCreate( (snapshot, context) => {
    //Do something in here:
});

But i have not been able to write to the second database in my http functions that are triggered by http requests, not database listeners.

I’m very grateful of any help on this, as I feel like I’m getting a bit of tunnel vision and need some fresh eyes. Thanks.

recreating interactive workspace in react. How to migrate?

So I originally created a program that allows an interactive workspace that allows users to drag around the page and move everything inside the container with it using pure JavaScript. code is as follows.

jsFiddle: https://jsfiddle.net/L05zorc7/2/

So as you can see in the example if you drag the blank space you can move the child in it.

But I want to migrate this program into a react component. I tried just doing this but it does not work.

import React, { useState, useEffect, useRef  } from 'react';
import './workspace.css'

const Workspace = () => {
  const workspaceRef = useRef<HTMLDivElement>(null);
  const workspaceContainerRef = useRef<HTMLDivElement>(null);


  // while the conf change, modify workspace accordingly
  const workspaceConf = new Proxy({ movementX: 0, movementY: 0, scale: 1 }, {
    set: (target, key, value) => {
      target[key as keyof typeof target]  = value;
      if (["movementX", "movementY"].includes(key as string) ) { // i.e., if movement changed
        if(workspaceRef.current){
          workspaceRef.current.style["translate"] = `${target.movementX}px ${target.movementY}px`;
        }
      }

      return true; // set handler should return true if success.
    }
  });

  // init workspace
  Object.keys(workspaceConf).forEach((key) => {
    workspaceConf[key as keyof typeof workspaceConf] = workspaceConf[key as keyof typeof workspaceConf];
  });

  // move the workspace while mouse dragging
  if(workspaceContainerRef.current){
    workspaceContainerRef.current.addEventListener("mousedown", e => {
    if (e.target !== workspaceContainerRef.current) return;
    // prevent unexpected workspace movement (e.g. while blocks being dragged)

    const move = (e:any) => { // mousemove event
      workspaceConf.movementX += e.movementX;
      workspaceConf.movementY += e.movementY;
    }

    document.body.addEventListener("mousemove", move);
    document.body.addEventListener(
      "mouseup",
      e => document.body.removeEventListener("mousemove", move), { once: true }
    );
    });}

  

  return (
    <div
    id="workspaceContainer"
      ref={workspaceContainerRef}
      style={{ width: "100vw", height: "100vh", margin: 0, padding: 0, overflow: "hidden" }}
    >
      <main
        id="workspace"
        ref={workspaceRef}
      >
        <div className="block">
          <div className="header">Sample</div>
          <div className="content">Yes</div>
        </div>
      </main>
    </div>
  );
};

export default Workspace;

And in the main App root component:

import React from 'react';
import WorkspaceComponent from './components/workspace';
//import Menu from './components/menu';

function App() {
  return (
    <>
      <WorkspaceComponent/>
    </>
    
  );
}
export default App;

It doesn’t seem like it is working can anyone help?

Can anyone give me a few lessons on how components work differently from pure js when it comes to dom manipulation?

I have tried using useState to track movement and useEffect ot modify css translate while movement state alters, but failed. So I resort to using an almost exact code from my original pure css code.

my approach using useState and useEffect Hooks

import React, { useState, useEffect, useRef  } from 'react';
import './workspace.css'

const Workspace = () => {

  const workspaceRef = useRef<HTMLDivElement>(null);
  const workspaceContainerRef = useRef<HTMLDivElement>(null);
  
  const [workspaceConfState, setWorkspaceConfState] = useState({
    movementX: 0,
    movementY: 0,
  });


  useEffect(() =>{
    if(workspaceRef.current !== null ){
      workspaceRef.current.style["translate"] = `${workspaceConfState.movementX}px ${workspaceConfState.movementY}px`;
    } 
  },[workspaceConfState])

  if(workspaceContainerRef.current){
    workspaceContainerRef.current.addEventListener("mousedown", (e: any) =>{
      if(e.target !== workspaceContainerRef.current) return;
      
      const move = (event:any) => {
        setWorkspaceConfState((prevConf) => ({
          ...prevConf,
          movementX: prevConf.movementX + event.movementX,
          movementY: prevConf.movementY + event.movementY,
        }));
      };
  
      document.body.addEventListener('mousemove', move);
      document.body.addEventListener(
        "mouseup",
        e => document.body.removeEventListener("mousemove", move), { once: true }
      );
      
    })
  }
  return (
    <div
    id="workspaceContainer"
      ref={workspaceContainerRef}
      style={{ width: "100vw", height: "100vh", margin: 0, padding: 0, overflow: "hidden" }}
    >
      <main
        id="workspace"
        ref={workspaceRef}
      >
        <div className="block">
          <div className="header">Sample</div>
          <div className="content">Yes</div>
        </div>
      </main>
    </div>
  );
};

export default Workspace;