Increase the day count by 1 on every third cycle

I've been working on a code to increment the days in a date variable every third iteration using modulus.

While I have managed to get the logic for every third iteration right, the day doesn't seem to increase by 1. I searched online and found suggestions to use

date.setDate(date.getDate() + 1);
, which I incorporated into my code. However, it only increments once and then remains stagnant.

Below is the code snippet of what I have experimented with:

for (let i = 0; i < 10; i++) {
                let date = new Date();
                if (i % 3 == 0) {
                    date.setDate(date.getDate() + 1);
                    console.log(date);
                }
            }

Answer №1

If you want to achieve your desired outcome, it's advisable to move the date variable outside of the loop. The code snippet below illustrates how this can be done, along with explanations on why it is necessary:

/* 
By moving "date" outside of the loop, you establish a fixed reference point
for incrementing during each iteration 
*/
let date = new Date();

for (let i = 0; i < 10; i++) {
 
  if (i % 3 == 0) {

    /*
    Increment the day of the date object that remains outside the loop.
    Since the date object is defined externally, these increments are retained
    across iterations of the loop
    */
    date.setDate(date.getDate() + 1);
    console.log(date);
  }
}

Answer №2

The issue lies in the fact that a new instance of the Date object is being created during each iteration of the loop. To resolve this, simply declare the variable date outside of the loop, as shown below:

let date = new Date();

for (let i = 0; i < 10; i++) {
  if (i % 3 == 0) {
    date.setDate(date.getDate() + 1);
    console.log(date);
  }
}

Answer №3

Make sure to declare the date variable outside of the loop to avoid resetting it unnecessarily.

let currentDate = new Date();
for (let j = 0; j < 4; j++) {
  if (j % 2 == 0) {
    currentDate.setDate(currentDate.getDate() + 1);
    console.log(currentDate);
  }
}

Answer №4

It's important to move the definition of your date variable outside of the loop to optimize performance.

let date = new Date();

for (let i = 0; i < 10; i++) {
  if (i % 3 == 0) {
    date.setDate(date.getDate() + 1);
    console.log(i, date);
  }
}

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

building a JSON object from scratch

After searching for multiple solutions to my problem, I have not been able to find a working code that fits the data I have. I am looking to transform this dataset into multiple objects: [{"creature":{"id":1,"name":"R.I.P.","sprite_location":null,"health ...

Is there a way to convert time measurements like minutes, hours, or days into seconds in React and then pass that information to an

Currently, I am working on an application that allows users to select a frequency unit (like seconds, minutes, hours, or days) and input the corresponding value. The challenge arises when I need to convert this value into seconds before sending it to the ...

Leverage promises to alter reactive data, strategically placing them to minimize the frequency of triggers being activated

Initial Method const list = reactive([1, 2, 3, 4, 5]); const clickHandler = () =>{ list.push(...[11, 12, 13, 14, 15]); list.push(...[16, 17, 18, 19, 20]); Promise.resolve().then(() => { list.push(33) ...

Misunderstanding the Variable Scope Concept in Node.js

I am struggling to comprehend why the return of an array from another function is confined to only one block of code. For example: exports.join = function(req, res){ User.findById(req.user._id, function(err, user) { var dupe = []; //placeholder arr ...

Using an array to dynamically input latitude and longitude into a weather API call in PHP

I am currently working on a leaflet map project that showcases the top 10 cities in a selected country. The markers are added dynamically based on the coordinates provided in the $latLng array. For example, when Australia is chosen from the select field, t ...

Submitting the form may cause disruptions for others

I currently have an email subscription form for my newsletter that is managed through PHP. This form appears in the footer of every page on my website. Check out a demonstration on JSFIDDLE While the form itself functions properly, I am encountering issu ...

What is the best method for incorporating multiple jQuery ready() functions?

Trying to develop a web application with HTML files that require multiple JS files. Need to specify tasks inside jQuery.ready() in each JS file, but unable to define $(function () {}) more than once. Is there a way to modify the passed function? index.pug ...

What is the method for accessing the locale and messages of the IntlProvider within a component?

My index.js file includes the following code: import trFi from './translations/fi_FI.json'; import trSv from './translations/sv_SE.json'; ReactDOM.render( <IntlProvider locale={my_locale} messages={{ fi: trFi, sv: trSv } ...

Troubleshooting JQuery Variable Overwriting Problem

Here is the code snippet I am working with: <script> $(document).ready(function() { var settings_image ={ url:"<?php echo site_url('/cms/editor/upload/images');?>", method: "POST", fileName: "file", returnType: ...

Is it possible to configure the jQuery datepicker to function without displaying the year?

I am looking to incorporate a datepicker into a project centered around historical events on specific dates. The concept is for users to select a day, such as "Nov. 20," and have the project display historical events from various years on that same day. ...

Dynamically include a new prop to the final element within an array of React components

I have been searching everywhere for a solution to this problem, but I can't seem to find one as I am unable to edit the props object. Here's what we are currently doing. We have a menu with subsections and we achieve this by: const firstSectio ...

Detecting collisions using CSS animation

I'm currently working on a unique "game" project. Check out the code snippet here: jsfiddle function update() { coyote.applyForce(gravity); coyote.edges(); coyote.update(); cactus.update(); if (coyote.intersects(cactus)){ alert("colisio ...

Is there a way to incorporate a D3 & Three.js object into a Vue 3 component seamlessly?

My goal is to build a Vue 3 component based on an object from D3 & Three.js created by Mike Bostock and found online. Here is the specific object I want to incorporate: https://bl.ocks.org/mbostock/2b85250396c17a79155302f91ec21224 The HTML code provi ...

Explain the function of the npm run build command and describe the role of webpack in generating a bundle file

Exploring the Contrasts: npm run build vs. npm install webpack Let's delve into the distinctions between these two commands ...

Changing the fill color of an SVG pattern remains unchanged

I have been working with Vue.js to create SVGs with shape patterns as background. The patterns themselves are functioning correctly, but I am encountering an issue when attempting to dynamically change the color of the pattern filling by passing props. D ...

What is the best way to retrieve an object within a class?

Exploring a Class Structure: export class LayerEditor { public layerManager: LayerManager; public commandManager: CommandManager; public tools: EditorTools; constructor() { this.commandManager = new CommandManager(); this.lay ...

What are the steps to designing a unique JSON data format?

When working with a JSON data structure containing 100 objects, the output will resemble the following: [{ "Value": "Sens1_001", "Parent": Null, "Child": { "Value": "Sens2_068", "Parent":"Sens1_001", "Child" : { ...

`Setting the response as an ArrayBuffer can be achieved on the client side, but it cannot be

I am working on a client-side form where I use XMLHTTPResponse to save response data as a file. In order to achieve this, the response type is set to arraybuffer using the following code: xhr.responseType = "arraybuffer"; While researching various method ...

Add styling to a window popup and close it when focus is lost in Ext JS

I am trying to implement a specific functionality where the popup arrow should be at the edge of the textbox as shown in the image below. How can I achieve this? Additionally, how can I make sure that clicking outside the control destroys the popup instead ...

Checking authentication globally using Vue.js

In the main blade file, I have the following code snippet: <script> window.App = {!! json_encode([ 'csrfToken' => csrf_token(), 'user' => Auth::user(), 'signedIn' => Auth::check() ...