Tips for showcasing a single item from an array every week

I'm in the process of developing a program where I share a new memory verse every week. Currently, I have code set up that displays each item with a delay based on my preference. However, I'd like to figure out how to showcase one item from an array each week and smoothly transition to the next without waiting a full week for the change. Here's what my current setup looks like:

<p id="wfm"></p>

var mind = [];
var i = 0;

var wfmind = document.getElementById('wfm');
function next_verse() {

     wfmind.innerHTML = mind[i % mind.length];
     i += 1;

}
setInterval(next_verse, 1000);

Answer №1

One way to generate an index is by using the current time, which starts counting from 1970 instead of the random time when the user visited the site.

At this moment, the current timestamp reads 1493684749486.

var d = new Date();
// +d === 1493684749486

To convert the current timestamp into an array index, first calculate the number of milliseconds in a week (1000*60*60*24*7), and then determine how many weeks have passed since 1970.

var index = Math.floor(+d / (1000*60*60*24*7));
// 2469 weeks have passed since 1970
// output `mind[index]` now.

For the purpose of this explanation, let's assume you want to update the item on Friday at 9 am. The nearest upcoming Friday at 9 am will be at timestamp 1494000000000.

d.setMilliseconds(0);
d.setSeconds(0);
d.setMinutes(0);
d.setHours(9);
d.setDate(d.getDate() + (7 + 5 - d.getDay()) % 7); // Find out how many days until Friday from Monday and add it to the current date.

This results in being 315250514 milliseconds away. You can use setTimeout with this delay to trigger the next update.

Once the item changes, set a new timeout for the following update. Using setTimeout for this purpose is recommended over setInterval.

function displayNextItem() {
  var d = new Date();
  var timestamp = +d;
  var index = Math.floor(timestamp / (1000*60*60*24*7));
  wfmind.innerHTML = mind[index % mind.length];

  d.setMilliseconds(0);
  d.setSeconds(0);
  d.setMinutes(0);
  d.setHours(9);
  d.setDate(d.getDate() + (7 + 5 - d.getDay()) % 7); // Find out how many days until Friday from Monday and add it to the current date.

  setTimeout(displayNextItem, +d - timestamp);
}
displayNextItem();

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

Adding styles to specific child nodes within a p-tree component in PrimeNG

Starting off with a demonstration example: Check out this StackBlitz for primeng p-tree. I am utilizing primeng to construct a structure for polls and answers using p-tree. The hierarchy is as follows: Participants --> Polls --> Questions --& ...

Transmit text from tinyMCE through AJAX in MVC architecture with PHP

I am currently facing an issue while trying to send POST data in the form of an array containing email elements such as subject and message. The problem arises when using tinyMCE for the subject part, which is not being sent through successfully. All other ...

Obtaining the camera's rotation in radians using Three.js

I've been struggling to grasp the concepts of quaternions for quite some time now, and I suspect they may be the root cause of my current challenge. If you're familiar with three.js, you might know about the equirectangular panorama video exampl ...

Update the navigation bar from displaying "LOGIN" to "LOGOUT

I am facing a challenge in updating the navbar login link to a logout link once the user logs in. I have attempted the following: header.ejs: <ul class="nav navbar-nav navbar-right"> <li id="home"><a href="/ ...

The requests I am sending to expressjs are not being processed asynchronously

const info = require('./randomfolder/info') app.get('/info', info.getInfo) app.listen(3000) // randomfolder/info: exports.getInfo = function(req, res) { setTimeout(function(){ res.send('example') }, 10000) } ...

"The sliding function of the React Bootstrap carousel is malfunctioning as it goes blank just before transitioning

Here is the code snippet I am working with: Whenever the carousel transitions to the next image, the current image disappears before displaying the next one. I am using react-bootstrap version 5.1.0, but it seems like there may be an issue with the transi ...

What is the process for delineating a smaller object within a larger one?

The current data structure I am handling: this.currentData = [ { "1304": { "id": 6458, "data": "Data1", "created_at": "2020-10-20 23:16:38", "updated_at": & ...

Should a Service Worker be automatically installed on each page reload, or only when a user navigates to a new page?

Currently in the process of developing a PWA. I have encountered an issue where the service worker seems to be installing on every page reload or when navigating to a different page within my app. It appears that many files are being cached during the inst ...

Angular logs the HTTP error before it is processed

When a user clicks on a button on a simple login form, a mechanism is triggered. This mechanism involves sending a POST request to a REST service with the user's provided credentials. If the credentials are correct, the success function is executed, o ...

Is it possible for you to simulate the shift key being pressed prior to the event execution?

Is there a way to allow the user to scroll left and right horizontally without having to hold the shift key down? I want to achieve this effect by setting the "shiftKey" variable to true even when it is not physically pressed. Any suggestions on how to ...

Managing and comparing category IDs in JavaScript to effectively store and render subcategories

My goal is to set the current category ID in a variable, and if the category changes, I want to store that as well. Then, I need to compare both IDs. If they are not equal, I want to set the subcategory to null. However, I am unsure of where my mistake lie ...

Error: The XML parsing in ASP failed to find a root element at the specified location

When clicking the button, I have jQuery/Ajax code that is supposed to pass the value of a selected radio button to a controller action and open a detail page. However, I am encountering an error. When using Mozilla Firefox, the console displays: XML Par ...

Providing Numpy Arrays as Input for a CNTK LSTM Neural Network

Is it possible to input sequence data as Numpy arrays into a text LSTM model defined in CTNK? Each instance in my dataset consists of sequences of integers that represent words, with varying lengths for each sequence. While it appears one can convert raw t ...

Having trouble decoding a cookie received from a React.js front-end on an Express server

When using React js for my front end, I decided to set a cookie using the react-cookie package. After confirming that the request cookie is successfully being set, I moved on to configure the Express server with the cookie parser middleware. app.use(cookie ...

React select and react modal cannot be overlaid on top of each other

I am facing an issue with my React modal that contains a react-select component. Some of the options at the bottom of the modal are not visible. How can I ensure that the select overlay appears on top of the modal to display all options? https://i.sstatic. ...

Step-by-step guide on updating a database using AJAX post serialization in PHP, jQuery, and JavaScript

I am facing an issue with updating my rooms table using the update query from serialize. Instead of saving all the data, it only updates the first row in the table. Here is my room list in the rooms table of my database: 1 Room1 Regular 2 Room2 ...

Express.js fails to handle HTTPS POST requests

I am facing an issue with serving HTTPS and listening to POST requests as the server is not responding to the request. My environment includes node 0.12.6 and express 4.13.3. I suspect that the routing configuration might be causing the problem, but I am ...

Ways to add a string to an array as a labeled object in javascript?

Is there a way to manipulate the array in imageCollection to achieve the format of the array in carouselPhotos as shown below? export default class HomeScreen extends Component { state = { imageCollection: [ { name: "P ...

When a button is clicked, I would like to direct the user to a webpage using a parameter retrieved from a separate function

Currently, I am facing difficulties with my course project. My program involves tracking user clicks on a series of images, with the variable 'n' representing the number of clicks, capped at a maximum of 3. I aim to redirect the user to a differe ...

Generate an empty matrix in Python

I am looking to initialize an empty 10*3*2 array using Python. Initially, I tried the following approach, but it did not work: parameters = [ [ [] * 2 ]*3 ] * 10 This resulted in a vector containing ten vectors, each with three [] elements: [[[], [], [ ...