How can I display my page rightaway when use startInterval on javascript? [duplicate]

I want to countdown date and hours and refresh it every 5minutes. When I use setInterval and setTime to 300000ms(5min) my countdown window showing after 5minutes. How can I do it display when I load a page and refresh every 5min?
Here is my code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JavaScript</title>
    <script>

let deadline = new Date("December 20, 2022, 00:00:00").getTime();

setInterval(function() {
  let today = new Date().getTime();
  let difference = deadline - today;
  let daycount = Math.ceil(difference / (1000 * 60 * 60 * 24));
  let hourcount = Math.ceil((difference % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
  document.getElementById("count").innerHTML =  daycount + " Days " + "and " + hourcount + " Hours " + "hours remain to 00:00, 20th December 2022.";
}, 300000);
    </script>
</head>
<body>
    <div id="count">
    </div>
</body>
</html>

In Chrome Dev Tools Memory profiler, what does the Array class signify

I have an angularJS app where I am trying to reduce memory leaks when closing a screen.
On closing the screen, I am calling the $destroy() to destroy the scope as well as remove its containing HTML. These both are working fine and when I check the Heap snapshots – I am using the 3 snapshot technique, I see that this worked.

But I noticed that the ‘Array’ and ‘Object’ are retaining quite some memory. And I could not find a way to decrease the retained memory.

Could someone tell me what does the ‘Array’ and ‘Object’ signify?
And how I can reduce the retained size?

The below is a screen shot from the chrome dev tools:

memory profiler snapshot

how to write a subquery inside join statement

This is my subquery:

const subquery = async () => {
  return await knex.select('*')
    .from('contracts')
    .where('estate_id', '=', estateid)
}

And this is how I’m inserting it into the join statement:

const data = await knex('clients')
  .join(await subquery(), 'clients.client_id', 'contracts.client_id')

But this result in an error, my question is what is the proper way to write a subquery and then include it inside a join statement, using async/await.

In the docs there is a mention on subqueries but is not for the join case and I fail at trying to adapt it to a join case:

knex('users').where('votes', '>', 100)

const subquery = knex('users')
  .where('votes', '>', 100)
  .andWhere('status', 'active')
  .orWhere('name', 'John')
  .select('id');

knex('accounts').where('id', 'in', subquery)

Vue computed with API results

I created an Anime Search App with Vue.js using the new script setup. I am fetching data from an API and I would like to display the number of search results displayed. Currently I am having trouble figuring out how to access those results. I have it displaying “50” for each result at the moment, but it is connected to the API’s original data I believe. Can someone help me figure this out please? I am a beginner to Vue and JS in general. Thank you very much!

Code for my search page:

 <template>
    <header>
            <div class="img-scroll img">
      <h1>Anime Search</h1>
      </div>
    </header>
            <main class="animeSearch">
            <form class="search-box" @submit.prevent="HandleSearch">
                    <input 
                        type="search" 
                        class="search-field" 
                        placeholder="Search for an anime..."
                        required
                        v-model="search_query" />
                </form>
                <p>{{ resultCount }} results!</p>
                <Swiper :slides-per-view="4" :space-between="50" class="cards" v- 
      if="animelist.length > 0">
                <SwiperSlide class="card" v-for="anime in animelist" 
                        :key="anime.mal_id"
                        :anime="anime">
                    
            <a :href="anime.url" target="_blank">
                <img 
                    :src="anime.image_url" 
                    :alt="anime.title + ' Poster'" 
                />
                <h3>{{ anime.title }}</h3>
            </a>
        </SwiperSlide>
                </Swiper>
                <div class="no-results" v-else>
                    <h3>Type in an Anime and hit 'enter' for search results.<br>
                    Use your cursor to swipe through images.<br>
                    Click on the image for information about the anime.<br>
                    Happy searching!...</h3>
                </div>
            </main>
             <footer>
      <p>&copy Megan Louise 2022</p>
      </footer>
    </template>

    <script>
    import { ref } from 'vue';
    import { Swiper, SwiperSlide } from "swiper/vue";
    import { computed } from "vue";
    import "swiper/css";
    export default {
      components: {
        Swiper,
        SwiperSlide,
      },
        setup() {
            const onSwiper = (swiper) => {
            console.log(swiper);
            };
            const search_query = ref("");
            const animelist = ref([]);
            const HandleSearch = async () => {
                animelist.value = await fetch(`https://api.jikan.moe/v3/search/anime? 
      q=${search_query.value}`)
                    .then(res => res.json())
                    .then(data => data.results);
                search_query.value = "";
            };
            const onSlideChange = () => {
            console.log('slide change');
            };
            const resultCount = computed(() => {
                return animelist.value.length;
                console.log('resultCount');
        });
            return {
                search_query,
                animelist,
                HandleSearch,
                onSwiper,
                resultCount,
                onSlideChange
            };
        },
    }
    </script>

    <style scoped>
    input[type='search'] {
    font-family: 'BIZ UDGothic', sans-serif;
    background-color: black;
    border: 2px solid #FD8721;
    color: #FD8721;
    width: 100%;
    height: 40px;
    padding: 5px;
    max-width: 600px;
    border-radius: 8px;
    margin-bottom: 40px;
    font-size: 22px;
    }
    h3 {
    color: #ECC013;
    text-shadow: 1px 1px #FD8721;
    font-weight: 400;
    }
    .cards {
        display: flex;
        flex-wrap: wrap;
        margin: 10px 40px;
        justify-content: space-evenly;
        cursor: pointer;
        }
    
    .card {
    width: 100%;
    max-width: 200px;
    height: auto;
    padding: 0px 8px;
    margin-bottom: 16px;
    }
    img {
        cursor: grab;
        width: 100%;
        height: 300px;
        object-fit: cover;
        border-radius: 16px;
        box-shadow: 0px 4px 8px rgba(0, 0, 0, 0.15);
        transition: 0.4s;
        border: 2px solid #BA1039;
    }
    img:hover {
            transform: scale(1.05);
        }
    @media only screen and (max-width: 820px) { 
    h1 {
    font-size: 3em;
    }
    }
    </style>

How to pass a jQuery varable as a URL in an API call?

Is there a way to add a jQuery string into a URL to pass along in an API call? I have a variable that has an input that contains a YouTube URL, it strips everything out except the ID of video.

So if the URL is https://www.youtube.com/watch?v=EQOGSl_YPqY, it strips everything out except EQOGSl_YPqY and it uses that to get data of the video via an API call.

So how do you apply the jQuery string in a URL to get data from an API call?

This is my code. I’m having problems with the URL:

$(document).on( "click", '#yt_run .acf-button-group', function() {
    var yt_url_raw = document.querySelector('.acf-fields div#yt_url.acf-field.acf-field-text.acf-field-60c3cc7056cc8 div.acf-input div.acf-input-wrap input');
    if(yt_url_raw.value.indexOf("https://www.youtube.com/watch?v=") !== -1){
        $.ajax({
            type:"GET",
            // error is here
            url:"https://www.googleapis.com/youtube/v3/videos?part=player,snippet&id=(yt_url_raw.value.replace('https://www.youtube.com/watch?v=', ''))&key=<?php echo $yt_settings;?>",
            success: function(data) {
                $(".acf-fields div.acf-field.acf-field-textarea.acf-field-6260f4adf1668 div.acf-input textarea").text(JSON.stringify(data));
            },
            dataType: 'JSON',
        });
});

React Native FlatList with position absolute behind Components

I have multiple SearchBar component, and when I search something it displays a FlatList, I want the Flatlist to be over the rest of the SearchBars components that are below, so I added position: absolute, but it only works with the first element, from the second element, the list displays behind the SearchBars, I also added zIndex: 100 to the List and to the container but it remains the same. The SearchBars are added with an array map:

export default function Game() {

    const arr = [0,1,2,3]
    const data = Data.players

    const [filteredData, setFilteredData] = React.useState([])
    const [actualPosition, setActualPosition] = React.useState(0)

    function search(text) {
        if(text.length < 3) return setFilteredData([])
        if(text.length >= 3){
            setFilteredData(data.filter(i => i.name.toLowerCase().includes(text.toLowerCase())))
        }
    }

    const getItem = (item) => {
        // Function for click on an item
        setActualPosition(actualPosition + 1)
        setFilteredData([])
    };  

    const ItemView = ({ item }) => {
        return (
            // Flat List Item
            <TouchableOpacity onPress={() => getItem(item)}>
                <View style={{flexDirection: 'row'}}>
                    <Text>{item.name}</Text>
                </View>
            </TouchableOpacity>
        );
    };
  
    return (
        <SafeAreaView style={styles.container} >
            {arr.map(i => {
                return (
                <View style={styles.container2} pointerEvents={actualPosition === i ? 'auto' : 'none'}>
                    <SearchBar
                        style={styles.searchBar}
                        placeholder="Search..."
                        onChangeText={(text) => search(text)}
                        onSearchPress={() => console.log("Search Icon is pressed")}
                        onClearPress={() => search("")}
                    />
                    {actualPosition === i && filteredData.length > 0 &&
                        <View style={styles.flatListContainer}>
                            <FlatList 
                                scrollEnabled={false}
                                style={styles.flatList}
                                data={filteredData}
                                keyExtractor={(item, index) => index.toString()}
                                renderItem={ItemView}
                            />
                        </View>
                        }
                </View>
                )
            })}     
        </SafeAreaView>
    );
} 

And the css is:

import { StyleSheet } from 'react-native';

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
  },
  container2: {
    flexDirection: 'column',
    width: '100%',
    alignItems: 'center',
  },

  searchBarContainer: {
    marginTop: 5,
    width: '125%'
  },
  searchBar: {
    borderBottomWidth: 0.75,
    marginBottom: 5
  },
  flatListContainer: {
    position: 'relative',
    marginLeft: 30,
    zIndex: 100,
    width: '100%'
  },
  flatList: {
    position:'absolute',
    zIndex: 100,
    borderWidth: 0.75,
    backgroundColor: 'white',
    width: '95%'
  },
});

export { styles };

I want all the lists to be displayed over the rest of the components, and why only works with the first element?

Thank you.

i am getting this error “Cannot find module ‘/var/app/current/src/server.js’. Please verify that the package.json has a valid “main” entry”

I am getting this error when i deploy a node project to Elastic Beanstalk after that i changed this code

main: src/server.js 

to

main: server.js

in the package.json file then i deleted every src keyword from the whole file.
now the amazon relational database service RDS gets connected, the server runs for a moment and they get disconnected as i can see in the log.
this is what’s in the folder i try to upload

config
controllers
.npmrc
aws.js
aws.js.map
package.json
sequalize.js
sequalize.js.map
server.js
server.js.map

these are the inbound rules of RDS

https://i.stack.imgur.com/XUSHF.png

so what do you suggest?

Can someone explain JS Event Loop?

So I kind of understand the JS event loop, but still have a few questions. Here is my scenario and a few questions.

So let’s say I have these functions:

  1. function1 – reads an absolute huge file.
  2. function2 – console.log(“Hey”);
  3. function3 – console.log(“What’s up”);

The way I am understanding this, and correct me if I’m wrong, what would happen is that the function1, function2, and function3, would be added to the queue. Then function1 would be added to the call stack followed by the next two functions.

Now the part where I’m confused is because the first function is going to take an extremely long time what happens to it? Does it get pushed somewhere else so that the next two functions are executed? I think the answer to this is that the only way it gets pushed somewhere else so that you can continue running is to make it an asynchronous function. And the way you make it a asynchronous function is either by using a callback function or promises. If this is the case how does it know that this is a asynchronous function? And where does it get pushed to so that the other two functions can be executed since they are relatively simple?

I think I answered the question myself but I keep confusing myself so if somebody could explain in extremely simple terms that would be great and sorry for the extremely stupid question.

Why doesn’t bootstrap work when I pull images to gallery in vue2

I work with vue2 for a new project, but I come across a problem with bootstrap. I have used firebase. I pull data from store/index.js(state, mutations, actions). I have pulled data but my bootstrap doesn’t work. All contents align toward below. They can’t be aligned abreast.

This is my projectPage component ;

 <template>
  <seciton id="projects">
    <div class="container text-center">
      <div class="row project-text header">
        <h6 class="upper-text text-capitalize">Project</h6>
        <h1 class="text-uppercase">Lastest Projects</h1>
      </div>
        <ProjectPageContent
          :post="post"
          v-for="(post, index) in galleryContent"
          :key="index"
        />
    </div>
  </seciton>
</template>

<script>
import ProjectPageContent from "./ProjectPageContent.vue";
export default {
  name: "ProjectPage",
  components: { ProjectPageContent },
  computed: {
    galleryContent() {
      return this.$store.state.galleryContent;
    },
  },
};
</script>

<style scoped>
#projects {
  min-height: 90vh;
  display: flex;
  justify-content: center;
  align-items: center;
}
#projects .project-text {
  margin-bottom: 25px;
}

</style>

This is my ProjectPageContent component ;

    <template>
          <router-link to="{ name: 'Project', params: { contentid: this.post.contentID } }">
           <div class="row g-3">
             <div class="col-xl-4 col-lg-6">
               <div class="project" data-aos="flip-up">
                <img :src="post.galleryPhotoURL" alt="" />
                 <div class="project-overlay">
                  <div>
                    <h4 class="d-flex align-items-start text-white">
                      {{ post.galleryTitle }}
                    </h4>
                    <h6 class="d-flex align-items-start text-white">
                     {{ post.gallerySubject }}
                    </h6>
                  </div>
                </div>
              </div>
            </div>
         </div>
       </router-link>
     </template>

  <script>
export default {
  name: "ProjectPageContent",
  props: ["post"],
};
</script>

<style scoped>
.project {
  position: relative;
  overflow: hidden;
  cursor: pointer;
  border-radius: 10px;
  box-shadow: 33px 33px 33px #d0d0d0, -13px -13px 13px #f8f8f8;
}
.project-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(46, 153, 121, 0.8);
  padding: 30px;
  display: flex;
  align-items: flex-end;
  transition: all 0.5s ease-in-out;
  opacity: 0;
}
.project img {
  width: 100%;
  height: 100%;
  transition: all 0.5s ease-in-out;
}
.project:hover .project-overlay {
  opacity: 1;
}

.project img {
  transform: scale(1.1);
}
.project:hover img {
  transform: scale(1.3);
}
.btn-primary {
  margin-right: 12px;
}
</style>

return to initial position when the mouse is no longer over it

I have this 3d parallax effect when the mouse hovers over the card. But I don’t know how to make it return to its original position when the mouse is no longer on it.

let cardParallx = document.querySelector('.card-active');

cardParallx.addEventListener('mousemove',(e)=>{
    let x =(window.innerWidth/2 - e.pageX)/30;
    let y =(window.innerHeight/2 - e.pageY)/30;
    cardParallx.style.transform =`rotateX(${-y}deg) rotateY(${-x}deg)`;
});
<div class="card-active">
<img src="https://placekitten.com/200/300">
</div>

How can I sync animation images from audio in Javascript/Typescript, language agnostic?

thanks for reading this question!

We are trying to create simple animations of, for example, a talking cartoon character. The challenge is to synchronize several images that correspond with certain ‘mouth shapes’, (closed lips for a P or B or M sound for example), with some unknown audio speaking potentially any words.

The audio can be in any language, though we will know what language it is as that is identified by the end user. Thus, the challenge requires some kind of syncing to the audio without being specifically stuck to English or another specific language.

I was thinking it might be possible to map an International Phonetic Alphabet (IPA) string to the images, but then the challenge is still to figure out how to somehow map the audio + language identifier to the right IPA string, and then to synchronize the right parts of the string to the right times in the audio.

If it helps, we do also have exact transcripts of the text that the audio is speaking.

If third party libraries are available for this kind of thing, they would be welcome, though our code base is in JS/TS only.

Thanks!

Copy Text To Clipboard using ReactJS

I’ve been stuck on this issue for a while now and couldn’t find anything to help me, so I would love if someone experienced could help me out on this.

lets say I have this const:

const test = "Hello World".

How can I have an onClick function on a button, where when I click it copies the string of test to the users clipboard?

Declare multiple document.getElementById(”); variables in few lines

I am making a chess game as a fun project. The way I have it set up involves one variable per square, which is taking me 64 lines of code as of right now.

The variable name should be the same as the ID.

My current code:

const a1 = document.getElementById('a1');
const a2 = document.getElementById('a2');
const a3 = document.getElementById('a3');
const a4 = document.getElementById('a4');
const a5 = document.getElementById('a5');
const a6 = document.getElementById('a6');
const a7 = document.getElementById('a7');
const a8 = document.getElementById('a8');

(goes on for 7 more sets of 8)

I have not tried anything else yet because I’m not sure where to start.

Are there any methods to shorten this? Thanks in advance!

Optioning chaining not working for array.length === x

if (products?.length !== 0) {
  console.log('true')
}

vs

if (product && products.length !== 0) {
  console.log('true')
}

If there is no product array, example 1 will still run the if statement. Shouldn’t the optional chaining check to see if product exists, then check for the length and finally check length to 0?

Example. 2 will not run if product does not exist.