Tips for updating innerHTML of multiple elements using setinterval?

I'm currently developing an application and I’m trying to implement a countdown timer for each element. However, when I pass the element to my function as it is, the countdown does not work. Surprisingly though, if I modify the function slightly by updating the innerHTML of the element outside of the setInterval, it starts functioning properly. I’m at a loss here. Any help would be greatly appreciated :) const timeout represents the element in question.

const json_content = json_reader(reserved)
for(let x=0; x<json_content["key"].length; x++){
    let tds = document.querySelectorAll(".display_content table td")
    for(let td of tds){
        new Vue({
        delimiters: ['[[', ']]'],
        el:td,
        data: { 
            display: "test",
            seats_number: "0",
        },
        methods:{
            test(){
                console.log("Hello")
            }
        },
        created: ()=>{
                const td_date = td.innerText
                if(td_date.includes(json_content["key"][x])){
                    const td_hour = td.nextElementSibling
                    const json_hour = json_content["value"][x]["times"]
                    if(Object.keys(json_hour).includes(td_hour.innerText)){
                        const seats = json_content["value"][x]["times"][td_hour.innerText]
                        const td_seat = td_hour.nextElementSibling
                        const timeout = td_seat.nextElementSibling
                        const seats_array = []
                        seats.forEach(element => {
                            const seat_json = json_reader(element)
                            seats_array.push(seat_json["key"]+":"+seat_json["value"])
                        });
                        this.seats_number = seats.length
                        td_seat.innerHTML = "<span onclick='display_seats(this.nextSibling)'>"+[[this.seats_number]]+"</span>"+"<span class='seats' value='"+seats_array+"'></span>"
                        counter(timeout)
                    } 
                }   
            }
        })
    }
}

and here's the counter function:

function counter(element){
    var t = 10
    setInterval(()=>{
        element.innerHTML = String(t)
        t -= 1
    },1000)

Answer №1

  1. Uncertain about where the counter function is being called.

<input type="number" id="inp">
<div id="counter"></div>
<script>
let input = document.getElementById('inp')
let counter = document.getElementById('counter')

let handleInput = e => {
let num = Number(e.target.value)
let _counter = num - 1
let timer = setInterval(_ => {
if(!_counter)
 clearInterval(timer)
counter.innerText =  _counter
_counter--
}, 1000)
}
input.addEventListener('input', handleInput)
</script>

However, something similar to the above code should be effective. Feel free to input numbers from 1-9 for testing.

  1. Another key point is verifying if the element passed is indeed the desired element. Consider adding a console.log(element) and inspect.

  2. Avoid directly updating the DOM, explore using ref or manipulating a variable initialized in data() which can be updated regularly, letting Vue take care of the rest.

new Vue({
  el: "#app",
  data: {
    timer: 20
  },
  mounted() {
setInterval(()=> this.timer--, 1000)
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  {{timer}}
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The code isn't able to make use of the MongoDB FIND method

When I attempt to search for items in a collection using the console with db.DB_NAME.find({ x: y }, it works perfectly. However, when trying to do the same in the code, it doesn't seem to work. It's worth mentioning that the findOne method works ...

Distinguishing between el and $el in Backbone.Js: What sets them apart?

I spent the entire afternoon struggling with this particular issue, but finally managed to resolve it. It ended up being a mix-up between assigning el and $el. Can anyone clarify the distinction between these two terms and provide guidance on when to use ...

Having trouble with filtering JSON data in AngularJS?

I'm sorry if this question has already been answered. I tried looking for solutions on other websites, but couldn't understand them. I am attempting to filter JSON data within the ng-repeat function, but whenever I try to input something, it does ...

Exploring the Differences between Angular's Http Module and the Fetch API

While I grasp the process Angular uses for HTTP requests, I find myself leaning towards utilizing the Fetch API instead. It eliminates the need to subscribe and unsubscribe just for a single request, making it more straightforward. When I integrated it int ...

Django development: Issue with log filtering in Python's logging module

I have a specialized logging filter class designed to exclude Django logs from my main logger 'bucket' (without disabling Django logs, just separating them into a different log): class ExcludeDjangoLogsFilter(logging.Filter): ""&quo ...

What is the method for initiating a radial gradient from the middle of the pie chart?

In my pie chart with grid lines, I have successfully implemented a radial gradient. However, the issue is that there is a separate gradient for each pie slice. What I really want is a single gradient originating from the center of the entire pie chart. I ...

Having trouble with Npx and npm commands not running in the VSCode terminal?

I am currently facing an issue while attempting to set up a react app in vscode using the command npx create-react-app my-app. It seems like the command is not working properly. Can anyone provide guidance on what steps I should take next? Despite watchin ...

An issue has arisen with AngularJS and Twitter Bootstrap, displaying an error message stating that the function element.focus

I recently implemented the angularjs twitter bootstrap datepicker and everything seemed to be working smoothly. However, I encountered an error when trying to click on the text box for the popup datepicker. This issue has left me puzzled as I am still new ...

What could be causing the No Reverse Match error I'm receiving?

I'm running into a problem while implementing the delete functionality in my Django project. Whenever I try to access the health_hub_history page, I seem to be stuck in a loop. Despite commenting out the relevant code in urls.py, I keep receiving the ...

How to use jQuery to dynamically set the value of a column span in a

Struggling with setting the value for a table column span. Here is my jQuery code: $('tr td data-th=Name span').val('My span content...'); This is how my HTML appears: <tr> <td data-th="Name"><span class="edit-inpu ...

Issues with injection of angularjs, sockjs, and angular-sockjs are causing functionality to not

As a newcomer to technologies like angular, sockjs-client, and cyclone, I've encountered an injection issue while attempting to utilize a component created by bendrucker. The component in question can be found at this link: https://github.com/bendruck ...

Issue: Connection Problem in React, Express, Axios

I've encountered an issue while attempting to host a website on an AWS EC2 instance using React, Express, and Axios. The specific problem I'm facing is the inability to make axios calls to the Express back-end that is running on the same instanc ...

The dropdown feature in the bootstrap4 navbar causes the navigation items to shift and adjust their

I am currently working on a navigation bar using Bootstrap4 and I've added a nav-item button to dropdown a menu. However, the issue I'm facing is that when the menu drops down, it pushes other nav-items around, causing them to change position. Th ...

Utilize a unique mesh instead of a generated one within three.js

Recently, I stumbled upon the fascinating world of three.js and I must say, it's quite amazing. After downloading some examples, I delved into exploring them. As someone who is new to coding in JavaScript, I find myself in need of assistance with mod ...

Having difficulty triggering the onchange event for a combo box programmatically in IE using JavaScript

I need to dynamically trigger the onchange function when the user changes the value of another combo box. Here's my code: HTML <select name="vbitratecontrol0" id="combo1" onchange="set()"> <option value="0">None</option> ...

Why does jQuery function properly in jsfiddle, but not in an HTML file?

I have been troubleshooting repeatedly, but I am unable to figure out why the jQuery code is not functioning as expected. Strangely enough, it works perfectly in jsfiddle! Here is the HTML code: <!doctype html> <html> <head> <meta ch ...

"Values are displayed accurately in the view, yet they do not appear correctly in the

I am having an issue with passing a report name to my template correctly in Django. The data is displaying correctly in the print report details, but it seems to be not getting passed correctly to the template. def profile(request): owner = User.objec ...

Link the first name of the user to the User model in Django using a foreign key

Currently, I am developing a blogging system without using Django's admin site. This means I have to create blog post models and views functions that manually store blog data in the database. One specific requirement is to include User login with cust ...

Updating the organization of the models directory in Loopback

I am looking to update the structure of the models folder. As per the documentation, I can make changes to the json config file which is typically set up like this: { "_meta": { "sources": [ "loopback/common/models/**/*", "loopback/serve ...

The HTML function transforms blank spaces into the symbol "+"

Just starting out with a question: I created a basic submission form, but I noticed that if there are any spaces in the inputs, the values get changed to a plus sign (+). Here's my form: <form name="input" action="search" method="get"> Web Ad ...