Utilize JavaScript to showcase a message based on the user's time measured in seconds

With a collection of 5000 text strings, each assigned a time value ranging from 0 to 86400 seconds...

I am looking to determine the user's current time and display the corresponding text string. Subsequently, as the user's time changes, I aim to update the displayed text to match the next sequential text string and continue this pattern.

Being relatively new to JavaScript, my initial idea involves utilizing two arrays – one to store the text strings and another for the associated times. The code would then locate the appropriate time from the 'time' array and reveal the text string with the matching index from the other array. In scenarios where the user's current time falls between two values, the lower value should be chosen.

Here is an example:

var interval = [0, 1728, 3456, 5184, 6912, 8640, ...]; // Array holding time intervals
var textstring = ["Verse 1", "Verse 2", "Verse 3", ...];     // Array containing text strings

function displayverse() {
    var now = new Date();
    var hour = now.getHours();
    var minute = now.getMinutes();
    var second = now.getSeconds();
    var currenttime = (hour * 3600) + (minute * 60) + second;

    for (var i = 0; i < interval.length; i++) {
        if (currenttime >= interval[i] && currenttime < interval[i + 1]) {
            document.getElementById('verse').innerHTML = textstring[i];
        }
    }
}


My current implementation seems to have issues, especially with the 'if' statement. Could someone provide insights on what could be wrong?

Current Code: https://jsfiddle.net/wrgt1/9bs4eu5q/1/

Answer №1

It seems like interval[i] in your code is not an array but a single value, which might be causing the issue of getting undefined when trying to access interval[i][0] or interval[i][1]. In order to retrieve the values correctly, you should only use interval[i] for the first value and interval[i+1] for the second one.

for (var i = 0; i < interval.length; i++) {
    if (currenttime >= interval[i] && currenttime < interval[i+1]) {
        document.getElementById('verse').innerHTML = textstring[i];
    }
}

Answer №2

Check out the updated snippet below, as there was a small coding error that needed to be corrected:

https://jsfiddle.net/ujfpy47a/

Corrected code snippet:

     for (var index = 0; index < interval.length; index++) {
        if (currentTime >= interval[index] && currentTime < interval[index+1]) {
          document.getElementById('verse').innerHTML = textString[index];
        }
      }

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

What is the best approach for presenting MySQL data on an HTML div through Node.js?

When working with Node.js, I prefer using Express as my framework. Here is the AJAX code I have on my member.ejs page: function load_member(){ $.ajax({ url: '/load_member', success: function(r){ console.lo ...

Each time I attempt to navigate to a different component by clicking on a button, I have experimented with using Link and Routes in React, but have been unsuccessful in

After clicking on a button following the first h1 tag, I want to open the AddProjects Component. However, despite using react-router-dom, an error keeps showing up. I think I might be using it incorrectly. Please help me correct it. import React from " ...

The integration of VueJS with the Canva Button JS API amplifies the

I have been exploring Canva's Button JS API which can be found at My goal is to implement a modular approach in utilizing their API, only loading the CanvaJS when necessary. My implementation involves triggering the load function when a button is cli ...

What is causing my component to render the count value twice?

This is my main layout component: function MainPage() { return( <div> <MLayout children={<MNavbar custOrFalse={false} />} /> </div> ); } export default MainPage; Here is the child navbar compone ...

Creating interactive web pages for scheduling tasks

I'm struggling with how to implement this concept. Imagine I have a School website that features a schedule page for 30 upcoming courses. When a course is clicked, it should lead to a new page displaying specific information about that course (such a ...

Unable to obtain a response even after providing the correct API key in a Node.js POST request

Can you please assist me in troubleshooting the POST request code below? Here is a snippet of the code: const express = require("express"); const bodyParser = require("body-parser"); //const request = require("request"); const https = require("https"); c ...

Guide to connecting an array with Doctrine 2 in Symfony 3

My repository function public function getBrandsByFilter($brands) takes an array parameter $brands. This array is retrieved from an ajax POST method and looks like this: $brands = ["brand" [ "caporal" => "caporal" "adidas" => "adid ...

What is the best way to smoothly transition from one video to another with a simple click?

I am looking to enhance my website by implementing a feature where a video will play when a button is clicked, and then another video will smoothly fade in while fading out the current video upon clicking a different button. This transition should dynamica ...

Error message "auth/code-expired" is triggered when Firebase Multi Factor Authentication for a web application detects that the verification code has expired

While working on adding multi-factor authentication to my Angular web application, I encountered an error message stating: "auth/code-expired", "The SMS code has expired. Please resend the verification code to try again.", even though I ...

Search for documents in MongoDB that have a key that exists and the value is set to true

I'm currently working on developing a customized ACL for my application. The structure of my data is shown below: { _id: ObjectId("345sdf345dsf"), allowedResources: { "GET /auth": true, "POST /verify": false ...

Is there a better method to accomplish this task in a more effective manner?

Is there a more efficient way to achieve this code with fewer lines of code? I'm looking for a solution that avoids repetition and makes it easier to manage, especially since I plan on creating multiple instances of this. Performance is a key consider ...

Combining Playwright and Cucumber for Seamless Integration

I am seeking guidance on integrating Playwright with Cucumber. What is the reason for using a Cucumber.js file instead of a Playwright.config.js file to set up the paths for Cucumber feature files and step definitions? If it's possible, How can we spe ...

The variable in my scope is not reflecting the changes in the HTML view

Here is my code for handling file attachments in AngularJS: $scope.attachments = []; $scope.uploadFile = function(files){ for(var i=0; i<files.length; i++){ $scope.attachments.push(files[i]); console.log($scope.attachments.length); } } ...

The command `grunt.option('force', true) isn't functioning properly

After reviewing the grunt.options documentation, my initial expectation was that I could initiate a Grunt task programmatically with the force option activated in this manner: var grunt = require('grunt'); grunt.option('force', true); ...

Unable to access path for children through buttons in parent path

As a data scientist entering the world of frontend development, I find myself faced with the task of creating a UI at the request of my boss. Please bear with me as I attempt to explain my issue in layman's terms. Currently, I am using Vue.js and hav ...

Tips for transferring data between various C# and JavaScript applications

On my ascx page, there is a div element that triggers a JavaScript function when clicked and sends an integer value. //HTML <div style="float: right; margin-right: 150px;" class="innerDivStyle" onclick="userStartExtend(2)"> < ...

Building module dependencies in the Dojo dojo

I'm in the process of utilizing the Dojo builder to compile a unified file that encompasses all the necessary modules for my application, excluding the application itself. Below is an illustration of a layer definition: layers: { 'dojo/dojo ...

JavaScript: handle null values along nested object keys by providing a default value

I am dealing with a complex JSON structure that requires pulling out specific information like this let result = data["a"]["b"][0]["c"]["d"][0]["e"][0] What is a streamlined approach to extract the data? A ...

React using Firebase: Receiving error "Cannot use import statement outside a module"

I've been following a helpful tutorial on setting up firebase authentication with React. However, I encountered some issues while trying to configure Firebase. I have created a firebase.js file as per the tutorial instructions: import firebase from &q ...

Retrieving data using parameters in Javascript

Just a quick overview, I am attempting to retrieve data from a URL using 2 parameters but I have no prior experience with JavaScript. Here is what I have tried: componentDidMount() { $input = array("team" => {teamName}, "name" =& ...