showing data in JSON format sequentially

My JSON data is structured like this:

[
"00-00-02":"first one",
"00-00-04":"the second",
"00-00-09":"third",
.
.
]

Is there a way to display, for example, first one at the specified time 00-00-02, and then show the next item at its time 00-00-04?
Please note: My aim is to accomplish this using JavaScript.

Answer №1

@Techie007 offers a clever solution for this scenario by utilizing unix timestamps. If you're unable to modify the JSON, consider implementing the following approach:

var data = {
"00-00-02":"first one",
"00-00-04":"the second",
"00-00-09":"third"
}
var timeout;
var start = new Date();
function displayMessage(){
    var now = new Date();
    var difference = now - start;
    var hours = Math.floor(difference / 600000);
    hours = (hours < 10)?"0" + hours : hours;
    var minutes = Math.floor((difference % 3600000) / 60000);
    minutes = (minutes < 10)?"0" + minutes : minutes;
    var seconds = Math.floor((difference % 60000 ) / 1000); 
    seconds = (seconds < 10)?"0" + seconds : seconds;

    if(data[hours + "-" + minutes + "-" + seconds]){
       console.log(data[hours + "-" + minutes + "-" + seconds]);
    }

    clearTimeout(timeout);
    timeout = setTimeout(displayMessage, 1000);
}


displayMessage();

Answer №2

When utilizing UNIX time, the comparison process becomes quite simple. Here's an example:

var info = {
   "1349598808" : "first option",
   "1349598845" : "the second one",
   "1349599400" : "third choice"
};

var current;
var secs;

setInterval(function(){
     current = new Date();
     secs = Math.round(current.getTime()/1000);
     if(info[secs] != undefined)
     {
          console.log(info[secs]);
          // Alternatively
          // Using PrototypeJS
          $("mydiv").update(info[secs]);
          // Or
          // Utilizing jQuery
          $("#mydiv").html(info[secs]);
     }
},1000);
​

Answer №3

If your data is in JSON format, you can easily iterate through the array by using the following code snippet:

var jsonData = {
  "00-00-02":"first element",
  "00-00-04":"second item",
  "00-00-09":"third one"
}

Object.keys(jsonData).forEach(function(key) {
  var value = jsonData[key];
  console.log("The " + value + " had a duration of " + key + " seconds")
});

Answer №4

If you want to trigger the functions "first-one", "the-second"..., then consider utilizing the setTimeout(fn, time) function with a calculated interval. An example of pseudocode could be:

data = ["00-00-02":"first one", "00-00-04":"the second", "00-00-09":"third",...];
//utilizing [key: value] notation
for (i=0; i<data.length; i++) {
    eventTime = timeInMilliSeconds(data[i].key);
    setTimeout(printMyMessage(data[i].value, eventTime);
}

Alternatively, you may opt to call the setTimeout() for data[i] within the function call printMyMessage() for data[i-1]. In this scenario, the second argument for the setTimeout() function would be the time difference between data[i] and data[i-1].

Answer №5

It's important to note that the option of video subtitles already exists, so there is no need to reinvent the wheel.

You can opt for the track element in HTML5, as explained here: http://www.html5rocks.com/en/tutorials/track/basics/. Alternatively, if you require more compatibility, consider using popcorn.js: .

If those options don't suit your needs, you could simply utilize a window.setTimeout method to display each subtitle.

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

Is there a way to create a function in JavaScript that eliminates duplicate Objects within an Array of Objects?

Currently, I'm working on a function to store details of a couch in a JS object with 3 properties locally. The properties include: An ID (obtained from the product URL using a function) A color (retrieved through an event listener) A quantity ...

It appears that vue.config.js is not loading properly

Here is a link to the code on CodeSandbox: https://codesandbox.io/s/dazzling-jepsen-r7283?file=/vue.config.js This code snippet is based on an answer from Stack Overflow. You can find it here: The code in vue.config.js is not being loaded by vue-cli. The ...

Is it possible that loading a JavaScript script in Chrome isn't functioning properly?

I am currently attempting to use Javascript to load the script below: function put() { var group = document.getElementById("obj_0123456790"); var children = group.childNodes; for( var i = 0; i < children.length; i++ ) { if( (ch ...

What is the best way to implement async/await in a for loop?

Utilizing async await within a for loop like so: for (let i = 0; i < result.length; i += 1) { try{ const client = await axios.get( `${process.env.user}/client/${result[i].id}` ); } catch(error){ console.log(error) } if (cl ...

Hiding a Div Using jQuery Depending on User's Choice

Currently, I am in the process of developing an employee directory using AJAX/jQuery with the assistance of the Random User Employee Directory API. You can access the data feed that I am utilizing by following this link: I have successfully created a webp ...

Guide to sending JSON data in Lua with cURL

Can someone help me with posting json in Lua using cURL? I've been searching online for examples but can't seem to find any. Here's the code snippet that I'm working with: c = curl.easy{ url = "http://posttestserver.com/pos ...

Is it possible to exchange a JavaScript array with JSON content in a Search Application?

Greetings to all you fantastic individuals! I have developed an application where the script search.js searches through a JavaScript array to display a list of results when a user types in a keyword into a search bar and hits enter. However, I am now facin ...

Send email without refreshing the page - no need for JQuery

I am attempting to create a form that can be submitted without refreshing the page. I am unable to utilize jQuery for this task. Despite my efforts, I haven't been able to find any solutions that do not involve jQuery. Therefore, I am seeking assistan ...

Modify CSS class if user is using Internet Explorer version 10 or above

I am attempting to modify the CSS of 2 ASP controls using jQuery specifically for users accessing the site with Internet Explorer 10 or 11. This adjustment is necessary because IE10 onwards, conditional comments are no longer supported. My approach to achi ...

What is the best way to continuously fetch the value of a dynamically updating p tag every 5 seconds?

Is there a way to constantly update the content of a changing p tag every 5 seconds? Here is my code snippet. var word; setInterval(function(){ $.get("http://localhost/chrome-notification/dosya.php", function (data) { callback(data); }); ...

Exploring Deeper with Interconnected Data Series

I am currently working on enhancing the display of drill-able data sets for multiple regions. My goal is to present both series simultaneously in order to allow for a direct comparison without the need to toggle between them. I envision a scenario where wh ...

Click Function for Modifying the Content of a Popup Window

I'm a beginner in JavaScript and I need help figuring out how to achieve the following task. Essentially, my goal is to have lines of code like this: <a onclick="JavascriptFunction(0000000)"><img src="image1.png"></a> The number w ...

differences in the reaction to special characters between IE10 and IE8

After searching extensively on Stack Overflow, I have yet to find a solution that addresses the unique challenge presented by my question. I have discovered that both dot and delete keys yield the same keycode (46) when checked for special characters. How ...

Guide to designing a unique shape in JointJs by combining multiple basic shapes together

Is there a way to combine different shapes in Joint JS, such as creating a custom shape that includes both a rectangle and a circle? I am aware of the path method, but I'm not sure if it is suitable for creating combined shapes like this. ...

Issue with JQuery on Mobile Devices: Troubles with Dropdown Menu and Loading Function

Having some trouble with my JQuery code on mobile devices. The drop down menu isn't showing up on an iPhone, the load function isn't working to display the additional PHP page on a Samsung Edge 7, and the drop down doesn't seem to be functio ...

Notifying with Socket.IO in Node.js

Hey there, I'm currently working on implementing a notification system but have hit a roadblock. I've sent an invitation to a user to join the club. socket.on("notify", async (message) => { // invite the user John Doe io.to('socke ...

What is the best way to transfer values from an iterated object in HTML to a component in Angular 2/4?

My Angular2/4 app allows for file uploads to S3. The setup is such that when a user uploads a file, it will be stored in an S3 bucket. Once uploaded, the user will be shown the list of files they have uploaded. In case they upload the wrong file by mistake ...

Guide on fetching data from a database using Node Js in a hierarchical structure

I am currently developing a NodeJs backend code to retrieve data from the database. The desired structure of the data should look like this: data = [{ name: "Admin", id: '1', children: [ { name: "Admin", id: "1& ...

Iteration through the entire array is not completed when utilizing a for loop with an if-else

I've hit a roadblock with a basic JS for loop and if else statement. I can't seem to figure it out, so I'm reaching out for some guidance. Below is the code snippet and here's the link to jsfiddle - https://jsfiddle.net/mauro_nappolini ...

Enhancing VueJS2 components by optimizing code structure to eliminate duplicate elements

The following code is used in two different components, so please avoid using props. Utilize data variables and largely similar methods but with different component templates. <template> </template> <script> export default { name ...