High CPU usage with ViewJS and maplibre-gl

I’m trying to integrate a simple map in my Vue.js app following the plusing dot example.

I’ve copied the code into my app like this:

<template>
  <div id="mapContainer" class="basemap"></div>
</template>

<script>
import maplibregl from 'maplibre-gl';

export function drawpulsingDot(map, lng, lat) {
    // https://maplibre.org/maplibre-gl-js-docs/example/add-image-animated/
    let size = 100

    if (map.hasImage('stationDot')) map.removeImage('stationDot')
    if (map.getLayer('stationDot')) map.removeLayer('stationDot')
    if (map.getSource('stationDot')) map.removeSource('stationDot')

    const pulsingDot = {
        width: size,
        height: size,
        data: new Uint8Array(size * size * 4),

// When the layer is added to the map,
// get the rendering context for the map canvas.
        onAdd: function () {
            const canvas = document.createElement('canvas');
            canvas.width = this.width;
            canvas.height = this.height;
            this.context = canvas.getContext('2d');
        },

// Call once before every frame where the icon will be used.
        render: function () {
            const duration = 1000;
            const t = (performance.now() % duration) / duration;

            const radius = (size / 2) * 0.3;
            const outerRadius = (size / 2) * 0.7 * t + radius;
            const context = this.context;

// Draw the outer circle.
            context.clearRect(0, 0, this.width, this.height);
            context.beginPath();
            context.arc(
                this.width / 2,
                this.height / 2,
                outerRadius,
                0,
                Math.PI * 2
            );
            context.fillStyle = `rgba(255, 200, 200, ${1 - t})`;
            context.fill();

// Draw the inner circle.
            context.beginPath();
            context.arc(
                this.width / 2,
                this.height / 2,
                radius,
                0,
                Math.PI * 2
            );
            context.fillStyle = 'rgba(255, 100, 100, 1)';
            context.strokeStyle = 'white';
            context.lineWidth = 2 + 4 * (1 - t);
            context.fill();
            context.stroke();

// Update this image's data with data from the canvas.
            this.data = context.getImageData(
                0,
                0,
                this.width,
                this.height
            ).data;

// Continuously repaint the map, resulting
// in the smooth animation of the dot.
            map.triggerRepaint();

// Return `true` to let the map know that the image was updated.
            return true;
        }
    };

    map.addImage('stationDot', pulsingDot, {pixelRatio: 2});
    map.addSource('stationDot', {
        'type': 'geojson',
        'data': {
            'type': 'FeatureCollection',
            'features': [
                {
                    'type': 'Feature',
                    'geometry': {
                        'type': 'Point',
                        'coordinates': [lng, lat]
                    }
                }
            ]
        }
    });

    map.addLayer({
        'id': 'stationDot',
        'type': 'symbol',
        'source': 'stationDot',
        'layout': {
            'icon-image': 'stationDot'
        }
    });
}

export default {
  name: "BaseMap",
  data() {},
  mounted() {
    this.map = new maplibregl.Map({
      container: 'mapContainer',
      style: 'https://api.maptiler.com/maps/voyager-v2/style.json?key=Q0mHUPCTF6KhlmRpN11W',
      center: [15, 53],
      zoom: 3.6
    })

    this.map.on('click', async e => {
      drawpulsingDot(this.map, e.lngLat.lng, e.lngLat.lat)
    })
  },
  methods: {}
}
</script>

<style scoped>
</style>

The thing is, when the pulsing dot is being rendered it uses 100% of by CPU, either on Chromium or Firefox.

Is there something wrong with using this library with Vue.js ? Is there a way to lower the GPU/CPU load for such a small animation ?

I’ve the issue with both maplibre and mapbox.

Thanks

I am using antd table to list data from an api but searching or filter functionality is not working

const [apiData, setApiData] = useState([]);

function getApiResponse(){
  fetch(`https://jsonplaceholder.typicode.com/comments`)
   .then(data=>setApiData(data));
}

let columns = [
        {
            title: 'Name',
            dataIndex: 'name',
            key: 'name',
        },
        {
            title: 'Email',
            dataIndex: 'email',
            key: 'email',
        }];

        function searchByCategoryName(inputSearch) {
        let searchInput = inputSearch.target.value;
        let output = apiData.filter((data) => {
            if ((data['name'].toLowerCase()).includes(searchInput.toLowerCase())) {
                return data;
            } else if (searchInput === '') {
                return data;
            }
        })
        setApiData(output);
    }


return(
      <>
        <Input onChange={(e)=>searchByCategoryName(e)}
        <Table dataSource={apiData} columns={columns} style={{ width: "100%" }} 
        scroll={{ y: 340 }} loading={loading} />
      </>
)

I am using antd table to list data form an api but searching or filter functionality is not working. When I am deleting the text from input it’s not listing the complete data. Some extend I know why it is happening but doesn’t not how to achieve expected output

passing react element into storybook prop [duplicate]

I have the code below in Page.jsx:

import React from 'react';
import PropTypes from 'prop-types'
import { Header } from './Header';
import './page.css';

export const Page = ({ children }) => {
  const [user, setUser] = React.useState();

  return (
    <article>
      <Header
        user={user}
        onLogin={() => setUser({ name: 'Jane Doe' })}
        onLogout={() => setUser(undefined)}
        onCreateAccount={() => setUser({ name: 'Jane Doe' })}
      />

      <section>
        { children }
      </section>
    </article>
  );
};
Page.propTypes = {
  children: PropTypes.element
}
Page.defaultProps = {
  children: <h1>foo</h1>
}

The below jsx does indeed work properly:

<Page>
   <h1>bar</h1>
</Page>

However, attempting to modify the children parameter through Storybook’s UI throws this error:
enter image description here
^before


enter image description here
^after


I believe this is because Storybook parses the input as a JSON. Is it possible to get it to parse the input as a React Element instead?

Why does VSCode console.log() return undefined while Fiddle or Browser Console give the correct value

I’m studying about the ‘this’ keyword inside regular function and arrow function, so following examples in stackoverflow I think that I had catched that, but one detail left unsolved for me. Please help me with that.
I dont know why but when I test the below code using VSCode the result is undefined, while using Fiddle or Chrome or Firefox the result is the expected.

As I had read, because of the fo2 function is called without bind any object so its ‘this’ keyword refers to global object, and ‘hi’ should be printed. It doesn’t happend using VSCode but yes using Browser Console or Fiddle.
I don’t use console.log() inside the functions to avoid returning undefined,as it has been explained before in other stackoverflow answers.
This is the code;

var greeting = 'hi';

const obj = {
  greeting: 'hey',

  fo() {
    const greeting = 'hello';

      function fo2 () {
        return this.greeting;
      };
      
      return fo2();  
  }  
};

console.log(obj.fo()); // 'hi' using browser console and Fiddle, but undefined using VSCode

how i can stop a setTimeout called inside a loop

i can’t stop a settimeout inside a loop even when i setCount(count => count = 0); how i can stop it when i setcount to 0 i tried async but it didn’t worked i found that setCount(count => count = 0) does not stop the setTimeout function inside the loop is that the setTimeout function is already scheduled to run and cannot be stopped by setting the state to 0.

import { useEffect, useRef, useState } from "react";
import Sim from "./Sim";

function Simon() {
  const [side, setSide] = useState<number[]>([]);
  const [Recordside, setRecordside] = useState<number[]>([]);
  const [count, setCount] = useState<number>(0)
  const [guess, setGuess] = useState<number>(0)
  const [play, setPlay] = useState<boolean>(false)
    // refs
    const buttonRef = useRef<HTMLButtonElement>(null);
    const greenRef = useRef<HTMLButtonElement | null>(null);
    const redRef = useRef<HTMLButtonElement | null>(null);
    const yellowRef = useRef<HTMLButtonElement | null>(null);
    const blueRef = useRef<HTMLButtonElement | null>(null);
    
  useEffect(() => {
    console.log("Recordside:", Recordside);
    console.log("side:", side);
    console.log("count:", count);
  }, [count, Recordside, side]);
  const clickPlay = () => {
    setPlay(true)
  }
  let reminder = async () => {
    // let guessing = Math.floor(Math.random() * 4)
    let delay = 200;
    const green = greenRef.current
    const red = redRef.current
    const yellow = yellowRef.current
    const blue = blueRef.current
    
    for (let i = 0; i <= count; i++) {
      setTimeout(() => {
        let currentGuess = Math.floor(Math.random() * 4);
        if (currentGuess === 0) {
          green?.classList.add("brightness-150")
        } else if (currentGuess === 1) {
          red?.classList.add("brightness-150")
        } else if (currentGuess === 2) {
          yellow?.classList.add("brightness-150")
        } else if (currentGuess === 3) {
          blue?.classList.add("brightness-150")
        }
        setSide(preSide => [...preSide, currentGuess]);
        setTimeout(() => {
          if (currentGuess === 0) {
            green?.classList.remove("brightness-150")
          } else if (currentGuess === 1) {
            red?.classList.remove("brightness-150")
          } else if (currentGuess === 2) {
            yellow?.classList.remove("brightness-150")
          } else if (currentGuess === 3) {
            blue?.classList.remove("brightness-150")
          }
          console.log("currentGuess", currentGuess);
        }, 400);
      }, delay);
      delay += 600;
    }
    const buttons = [green, red, yellow, blue];
    buttons.forEach((button, index: number) => {
      button ? button.onclick = () => {
        if (index < 4) {
          setRecordside(prevRecordside => [...prevRecordside, index]);
        }
      } : null;
    });
    
    if(side.length === Recordside.length && Recordside.join(" ") === side.join(" ")) {
      setCount(prevCount => prevCount + 1);
    } if(side.length === Recordside.length && Recordside.join(" ") !== side.join(" ")) {
      setCount(count => count = 0);
      setRecordside(prevRecordside => prevRecordside = []);
      setSide(prevside => prevside = []);
      console.log("no")
    }      
  };
  return (
    <div className="relative flex flex-col justify-center items-center">
      <div>
        <Sim ref={greenRef} color= "bg-green-500" angle= "rounded-tl-full" />
        <Sim ref={redRef} color= "bg-red-500" angle= "rounded-tr-full" />
      </div>
      <div>
        <Sim ref={yellowRef} color= "bg-yellow-400" angle= "rounded-bl-full" />
        <Sim ref={blueRef} color= "bg-blue-500" angle= "rounded-br-full" />
      </div>
      <button className="absolute border-none bg-neutral-900 text-white hover:outline-none focus:outline-none text-xl sm:text-2xl font-bold rounded-full w-[150px] sm:w-[175px] h-[150px] sm:h-[175px] transition duration-200 hover:scale-105" onClick={() => reminder()}>Play</button>
    </div>
  );
}

export default Simon;

How to load Google Maps libraries correctly?

I am making a map, using Google api.
How to load all needed maps libraries correctly?
I get ‘google is not defined’

<script src=" https://maps.googleapis.com/maps/api/js?key=key&callback=initMap&libraries=maps" async defer></script>

Must I put v.3exp or something else?

Is this code good?

<script>
        let map;
        function initMap() {


            map = new window.google.maps.Map( document.getElementById( 'map' ), {
                center: {
                    lat: 51.513329,
                    lng: -0.088950
                },
                zoom: 14
            });



        }



google.maps.event.addDomListener(window, 'load', initialize); //error here
google.maps.event.addListener(map, 'click', function(event) {document.write('Hi');});

    </script>

I tried all variants, no work

JavaScript mini project – API- Axios – show me result twice

I have a mini project for ask API “https://hacker-news.firebaseio.com/v0/newstories.json”

That send me a object with the last 500 id news . Then I use this ID to ask API “https://hacker-news.firebaseio.com/v0/item+ID+.json” that send me the detail for one news.

I have to manage Axios.
The file works but send me every result / console log TWICE?
thank you for the support.

main.js

import createGeneralElement from "./createElement.js";
const API_500_NEWS = "https://hacker-news.firebaseio.com/v0/newstories.json"; // define API_500 const
const API_ONE_NEWS = "https://hacker-news.firebaseio.com/v0/item/"; // define fix part of One news Api const

//let array_id_news = []; //
let actual_index = 0; // inizalmente ho l'indice di notize "date" a 0
let news_per_page = 2; // come da richiesta verranno visualizzate 10 news alla volta

//var _ = require("lodash"); // import lodash
///// test axios //////////////////////////////////////
import axios, { isCancel, AxiosError } from "axios"; // import axios
import "../scss/main.scss"; // import scss for webpack

function createUrl(index) {
  let NewUrl = `${API_ONE_NEWS + index + ".json"}`;
  return NewUrl; // No promise - normal function
}

function getOneNews(index) {
  return axios.get(createUrl(index)); // promise
}

function getData() {
  return axios.get(API_500_NEWS); // promise
}

async function getXnewsPerPage(array_id_news) {
  //array_id_news = await genArray500();

  for (let i = actual_index; i < actual_index + news_per_page; i++) {
    let newsX = await getOneNews(array_id_news[i]);

    console.log("i :", i);
    console.log(i, "newsX :", newsX.data);
  }
  actual_index = news_per_page + actual_index;
  console.log("actual index ***************************:", actual_index);
}

window.addEventListener("DOMContentLoaded", () => {
  getData().then((res) => {
    console.log("test res.data :", res.data);
    getXnewsPerPage(res.data);
    createGeneralElement("header", "my-header", "prova header"); // function createGeneralElement(tagHtml, className, content)
  });
});

createElement.js

const body = document.body;
// Function for create general elements
export default function createGeneralElement(tagHtml, className, content) {
  const newElement = document.createElement(tagHtml);
  newElement.innerHTML = content;
  newElement.classList.add(className);
  newElement.setAttribute("id", className);
  body.appendChild(newElement);
}

Custom hook taking parameters from another function

I am having a progress bar which on click starts its progress from 60 to all the way upto 10 for each of the file of files array. I am a using the ref to dymanically increment the progress by 10 and when its 100, I clear it and bring the message as Upload Complete. Code works just fine.
I have moved the mechanism of initiating progress onto a custom hook, that basicallly takes setter, the interval and a file name for which it has to update upload progress.
I am initializing the hook inside the parent, but each of the file name I will only get when I click each of the file names button. how can I pass the name of the file?

Sandbox: https://codesandbox.io/s/progress-bar-r0zcjn?file=/src/App.js

Component:

import React, { useState, useRef } from "react";
import "./styles.css";
import ProgressBar from "./ProgressBar";
import useProgress from "./useProgress";

const appStyles = {
  height: 20,
  width: 500,
  margin: 50
};

export default function App() {
  const [files, setFiles] = useState([
    { name: "file1", status: 0 },
    { name: "file2", status: 0 },
    { name: "file3", status: 0 }
  ]);

  const initiateProgress = useProgress(setFiles, 60);

  const initiate = (name) => {
    console.log(name);
  };

  return (
    <div className="App" style={appStyles}>
      {files.map((file) => {
        return (
          <div key={file.name}>
            <button type="button" onClick={() => initiate(file.name)}>
              {file.name}
            </button>
            <ProgressBar bgColor={"#DF8100"} progress={file.status} />
            {file.status === 100 && <span>Upload complete</span>}
          </div>
        );
      })}
    </div>
  );
}

Hook

import { useRef } from "react";

const useProgress = (updater, timer, name) => {
  const mockRef = useRef(timer);

  const handleProgress = () => {
    const intervalID = setInterval(() => {
      if (mockRef.current >= 100) {
        clearInterval(intervalID);
        updater((prevState) =>
          prevState.map((item, itemIndex) =>
            item.name === name ? { ...item, status: 100 } : item
          )
        );
      } else {
        mockRef.current = mockRef.current + 10;
        updater((prevState) =>
          prevState.map((item, itemIndex) =>
            item.name === name ? { ...item, status: mockRef.current } : item
          )
        );
      }
    }, 200);
  };

  return handleProgress;
};

export default useProgress;

State variable doesn’t get updated in ReactJS

Sample JSON:

{
  "tutor_id": "1",
  "first_name": "Martin",
  "last_name": "Smith",
  "grade": "Senior",
  "subject": "Integral Calculus",
  "subjects": [{ "subject_id": "2", "subject": "Linear Algebra" }]
}

My goal is to access "subject":"Linear Algebra" in the latter part of the JSON above. tutorDetails.subjects works but tutorDetails.subjects[0] returns an error that ‘0’ is undefined.

Error

My Code:

import React, {useState, useMemo} from "react";
import Button from '@mui/material/Button';
import Dialog from '@mui/material/Dialog';
import DialogActions from '@mui/material/DialogActions';
import DialogContent from '@mui/material/DialogContent';
import DialogContentText from '@mui/material/DialogContentText';
import DialogTitle from '@mui/material/DialogTitle';
import Slide from '@mui/material/Slide';
import axios from 'axios';

 function TutorCard({tutor_id, first_name, last_name, grade, subject}) {
    return (
        <div className="md:flex bg-white shadow text-gray-800 my-4 py-4 px-10 rounded-md items-center justify-between hover:bg-gray-300"  >
            {/* <img
                style={{ maxWidth: "60px"}}
                className="rounded-full shadow-md border border-gray-300"
                src={image}
                alt="employee"
            /> */}
            <p className="font text-md" style={{ color: 'black', textAlign: "center"}}>{tutor_id}</p>
            <p className="font text-md" style={{ color: 'black', textAlign: "center"}}>{first_name}</p>
            <p className="font text-md" style={{ color: 'black', textAlign: "center" }}>{last_name}</p>
            <p style={{ color: 'black', textAlign: "center" }}>{grade}</p>
            <p style={{ color: 'black', textAlign: "center" }}>{subject}</p>
            <AlertDialogSlide tutorID = {tutor_id} firstName = {first_name} lastName = {last_name} grade = {grade} subject = {subject} />
        </div>
    )
}




const Transition = React.forwardRef(function Transition(props, ref) {
  return <Slide direction="up" ref={ref} {...props} />;
});

function AlertDialogSlide(props) {
  const [open, setOpen] = React.useState(false);

  const handleClickOpen = () => {
    setOpen(true);
  };

  const handleClose = () => {
    setOpen(false);
  };

  const [tutorDetails, setTutorDetails] = useState([ ])

components (componentDidMount, componentWillMount)
    useMemo( () => {
    const retrieveData = async () => {
        const resp = await axios.get('API call' + props.tutorID);
        console.log("Tutor Info Response: " + JSON.stringify(resp.data));
        console.log("AltSubjects: " + JSON.stringify(resp.data.subjects[0]));
        setTutorDetails(resp.data);

    }

    retrieveData();
}, []);

    

  return (
    <div>
      <Button variant="outlined" onClick={handleClickOpen}>
        {'>'}
      </Button>
      <Dialog
        open={open}
        TransitionComponent={Transition}
        keepMounted
        onClose={handleClose}
        aria-describedby="alert-dialog-slide-description"
        fullWidth = {true}
      >
        <DialogTitle>{props.firstName + " " + props.lastName}</DialogTitle>
        <DialogContent>
          <DialogContentText >
            <strong>Level: </strong> {props.grade} <br/>
            <strong>Subject: </strong> {props.subject} <br/>
            {/* <div> {(tutorDetails.subjects).map(sub => <div>  <strong>Alternative Subject: </strong> {JSON.stringify(sub)} <br/> </div>)} </div> */}
            <strong>Alternative Subject: </strong> {tutorDetails.subjects[0]} <br/>
          </DialogContentText>
        </DialogContent>
        <DialogActions>
          <Button onClick={handleClose}>Close</Button>
        </DialogActions>
      </Dialog>
    </div>
  );
}
export default TutorCard;

I tried researching through other resources but, nothing has helped so far.

How do I add target=”_blank” to a link within a specified div with AJAX?

I find this code by @artlung here

/* here are two different ways to do this */
//using jquery:
$(document).ready(function(){
  $('#link_other a').attr('target', '_blank');
});

and and tweaked it to work with popup links

$(document).ready(function(){
  $('#newsflash').on('click', 'a', function(){
    $(this).attr('target', '_blank');
  });
});

Please use it. Hope this helps someone 🙂

How to push all object into one object array based on some conditions

I have an array of objects, I want to push it to one object if certain condition meet.
I want to group data based on some conditions. but I want to push it to one array instead of making it parent and child.

Here is my object array

var myData = [{
    "portfolio": "Consumer",
    "regiserDate": "2021-01-27",
    "sendType": "Capitalization",
    "amount": 20,
    "__typename": "taxCalculation"
}, 
 {
    "portfolio": "Commercial",
    "regiserDate": "2021-02-27",
    "sendType": "Accure",
    "amount": 20,
    "__typename": "taxCalculation"
}, 
 {
    "portfolio": "Commercial",
    "regiserDate": "2021-02-27",
    "sendType": "Capitalization",
    "amount": 20,
    "__typename": "taxCalculation"
}, 
 {
    "portfolio": "Commercial",
    "regiserDate": "2021-01-27",
    "sendType": "Accure",
    "amount": 20,
    "__typename": "taxCalculation"
}, 
 {
    "portfolio": "Commercial",
    "regiserDate": "2021-04-27",
    "sendType": "Capitalization",
    "amount": 20,
    "__typename": "taxCalculation"
}, 
 {
    "portfolio": "Retail",
    "regiserDate": "2021-05-27",
    "sendType": "Capitalization",
    "amount": 20,
    "__typename": "taxCalculation"
}, 
 {
    "portfolio": "Retail",
    "regiserDate": "2021-06-27",
    "sendType": "Capitalization",
    "amount": 20,
    "__typename": "taxCalculation"
}, 
 {
    "portfolio": "Retail",
    "regiserDate": "2021-02-27",
    "sendType": "Capitalization",
    "amount": 20,
    "__typename": "taxCalculation"
}, 
 {
    "portfolio": "Retail",
    "regiserDate": "2021-07-27",
    "sendType": "payable",
    "amount": 20,
    "__typename": "taxCalculation"
}, 
 {
    "portfolio": "Retail",
    "regiserDate": "2021-01-27",
    "sendType": "Accure",
    "amount": 20,
    "__typename": "taxCalculation"
}, 
 {
    "portfolio": "Retail",
    "regiserDate": "2021-09-27",
    "sendType": "Accure",
    "amount": 20,
    "__typename": "taxCalculation"
}, 
 {
    "portfolio": "Consumer",
    "regiserDate": "2021-08-27",
    "sendType": "Accure",
    "amount": 20,
    "__typename": "taxCalculation"
}, 
 {
    "portfolio": "Consumer",
    "regiserDate": "2021-09-27",
    "sendType": "Accure",
    "amount": 20,
    "__typename": "taxCalculation"
}, 
 {
    "portfolio": "Consumer",
    "regiserDate": "2021-11-27",
    "sendType": "Accure",
    "amount": 20,
    "__typename": "taxCalculation"
}, 
 {
    "portfolio": "Retail",
    "regiserDate": "2021-11-27",
    "sendType": "Accure",
    "amount": 20,
    "__typename": "taxCalculation"
}, 
 {
    "portfolio": "Retail",
    "regiserDate": "2021-01-27",
    "sendType": "payable",
    "amount": 20,
    "__typename": "taxCalculation"
}, 
 {
    "portfolio": "Retail",
    "regiserDate": "2021-01-27",
    "sendType": "Accure",
    "amount": 20,
    "__typename": "taxCalculation"
}, 
 {
    "portfolio": "Consumer",
    "regiserDate": "2021-01-27",
    "sendType": "Accure",
    "amount": 20,
    "__typename": "taxCalculation"
}, {
    "portfolio": "Consumer",
    "regiserDate": "2021-12-27",
    "sendType": "Accure",
    "amount": 20,
    "__typename": "taxCalculation"
}, 
 {
    "portfolio": "Consumer",
    "regiserDate": "2021-11-27",
    "sendType": "payable",
    "amount": 20,
    "__typename": "taxCalculation"
}, 
 {
    "portfolio": "Consumer",
    "regiserDate": "2021-01-27",
    "sendType": "AccureAccureAccure",
    "amount": 20,
    "__typename": "taxCalculation"
}, 
 {
    "portfolio": "Consumer",
    "regiserDate": "2021-01-27",
    "sendType": "AccureAccure",
    "amount": 20,
    "__typename": "taxCalculation"
}, 
 {
    "portfolio": "Consumer",
    "regiserDate": "2021-01-27",
    "sendType": "Accure",
    "amount": 20,
    "__typename": "taxCalculation"
}, 
 {
    "portfolio": "Consumer",
    "regiserDate": "2021-04-27",
    "sendType": "Capitalization",
    "amount": 20,
    "__typename": "taxCalculation"
}, 
 {
    "portfolio": "Commercial",
    "regiserDate": "2021-07-27",
    "sendType": "payable",
    "amount": 20,
    "__typename": "taxCalculation"
}, 
 {
    "portfolio": "Commercial",
    "regiserDate": "2021-07-27",
    "sendType": "Capitalization",
    "amount": 20,
    "__typename": "taxCalculation"
}, 
 {
    "portfolio": "Commercial",
    "regiserDate": "2021-08-27",
    "sendType": "Accure",
    "amount": 20,
    "__typename": "taxCalculation"
}, 
 {
    "portfolio": "Commercial",
    "regiserDate": "2021-01-27",
    "sendType": "payable",
    "amount": 20,
    "__typename": "taxCalculation"
}, 
 {
    "portfolio": "Commercial",
    "regiserDate": "2021-05-27",
    "sendType": "payable",
    "amount": 20,
    "__typename": "taxCalculation"
}
];

I want to combine into one array object if “portfolio” and “sendType” are same.
my expected result should be like

var result = [{
    "portfolio": "Consumer",
    "sendType": "Capitalization",
    "regiserDate": "2021-01-27",
    "amount": 20,
    "regiserDate": "2021-02-27",
    "amount": 20,
    "regiserDate": "2021-03-27",
    "amount": 20,
    "regiserDate": "2021-04-27",
    "amount": 20,
    "regiserDate": "2021-07-27",
    "amount": 20,
    "regiserDate": "2021-09-27",
    "amount": 20,
    "regiserDate": "2021-08-27",
    "amount": 20,
    "__typename": "taxCalculation"
}, 
{
    "portfolio": "Consumer",
    "sendType": "Accure",
    "regiserDate": "2021-05-27",
    "amount": 20,
    "regiserDate": "2021-01-27",
    "amount": 20,
    "regiserDate": "2021-02-27",
    "amount": 20,
    "regiserDate": "2021-09-27",
    "amount": 20,
    "regiserDate": "2021-06-27",
    "amount": 20,
    "regiserDate": "2021-04-27",
    "amount": 20,
    "regiserDate": "2021-04-27",
    "amount": 20,
    "__typename": "taxCalculation"
},
{
    "portfolio": "Commercial",
    "sendType": "Accure",
    "regiserDate": "2021-05-27",
    "amount": 20,
    "regiserDate": "2021-01-27",
    "amount": 20,
    "regiserDate": "2021-02-27",
    "amount": 20,
    "regiserDate": "2021-09-27",
    "amount": 20,
    "regiserDate": "2021-06-27",
    "amount": 20,
    "regiserDate": "2021-04-27",
    "amount": 20,
    "regiserDate": "2021-10-27",
    "amount": 20,
    "__typename": "taxCalculation"
},
{
    "portfolio": "Retail",
    "sendType": "payable",
    "regiserDate": "2021-05-27",
    "amount": 20,
    "regiserDate": "2021-01-27",
    "amount": 20,
    "regiserDate": "2021-02-27",
    "amount": 20,
    "regiserDate": "2021-09-27",
    "amount": 20,
    "regiserDate": "2021-06-27",
    "amount": 20,
    "regiserDate": "2021-04-27",
    "amount": 20,
    "regiserDate": "2021-04-27",
    "amount": 20,
    "__typename": "taxCalculation"
}
]

Countdown timer won’t stop looping

I’ve been practicing my count-down timers using Javascript and decided I wanted to try and automate it a bit. What I hope to happen is the user selects a date using a form input=date, and then that date is read with an onBlur attribute. The onBlur then activates a function to start the timer and passes the value of the calendar to the function.

My issue is not getting the timer to work. That works absolutely fine, my issue is getting it to stop or to update if a new date is chosen.

Currently what happens on expiration is the textContent is changed to “Expired” for exactly 1 tick, and then is replaced with the original countdown timer again. Similarly if the date is changed, it will flick between 2 different timers with the 2 different dates in.

I’ve tried using an additional function to call the countdown function. I’ve tried making a boolean switch to true once the timer’s started to stop an update, I’ve tried using If statements at the end of my countdown timer, as well as the clearInterval method. So far I can’t get it to stop this never-ending loop.

Any help on this would be greatly appreciated. I can see what’s happening – the setInterval keeps looping, and the placeholder text has been changed. The clearInterval method doesn’t appear to be stopping the timer either. Also my variable 'theTimer' which stores the countdown has a value of 5, for whatever reason. I just don’t know how to resolve this at the moment. I feel it’s getting a continual value feed from the calendar which keeps firing the function, just not sure.

<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">

<head>
  <title>Practice</title>

</head>

<body>
  <form>
    <input type="date" id="calander-input" onblur="userDeadlineTimer(value)" /><br />

  </form>
  <h3>Time until date:</h3>
  <p id="user-deadline">0 days 0 hours 0 minutes 0 seconds</p>
  <script>
    //Javascript
    function userDeadlineTimer(value) {
      let userDeadline = new Date(value).getTime();
      //console.log("The userdeadline is " + userDeadline);
      var theTimer = setInterval(function() {
        let userReference = new Date().getTime();
        let userDelta = userDeadline - userReference;


        //Find the days

        let userDays = Math.floor((userDelta / (1000 * 60 * 60 * 24)));
        // console.log(userDays);

        //find the hours

        let userHours = Math.floor((userDelta % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
        //console.log(userHours);

        //Find the minutes

        let userMinutes = Math.floor((userDelta % (1000 * 60 * 60)) / (1000 * 60));
        //console.log(userMinutes);

        //Find the seconds

        let userSeconds = Math.floor((userDelta % (1000 * 60)) / (1000));
        //console.log(userSeconds);


        if (userDelta > 0) {
          document.getElementById("user-deadline").textContent = userDays + " days " + userHours + " hours " + userMinutes + " minutes " + userSeconds + " seconds.";
        } else {

          clearInterval(theTimer);

          document.getElementById("user-deadline").textContent = "Expired";
        }


      }, 1000);

    }
  </script>
</body>
</html>

JSON.parse is not working on windows server but is working on other windows verision

When I run this code in windows server 2012 R2

<!DOCTYPE html>
<html>
   <script src="jquery.min.js"></script>
<body>
</body>
</html> 
 <script type="text/javascript">
  $(document).ready(function(){ 
                 $.ajax({            
                           url: "api.php",
                           type:"POST",
                           data:{
                               card_no:"1017",
                               },
                           success:function(response){
                               console.log(response);
                               var json_data = JSON.parse(response);
                                                    },
                       });
  });
</script>

Uncaught SyntaxError: JSON.parse: unexpected end of data at line 3 column 1 of the JSON data

But the same codes run smoothly on other version of windows
any help will be apriciated