Increment or decrement a number using setTimeout in JavaScript

Having trouble with incrementing and decrementing a number using a timer in my code. It seems to not be working properly...

let num = 0,
maxNum = 5,
timerFunc = function() {
    if (num < maxNum) {
        num++;
        console.log(num); //working fine
    } 

    if (num == maxNum) {
        num--;
        console.log(num); //not functioning as expected
    }

    setTimeout(timerFunc, 60); 
}; 

timerFunc(); 

Answer №1

At the count of 5, the second if statement triggers a change to 4, only to be followed by the first if statement returning it back to 5.

let i = 0,
maxCount = 5,
direction = 0; // 0 for up, 1 for down.

let countdown = function() {
    if (direction == 0) {
        i++;
        console.log(i)
    }

    if (direction == 1) {
        i--;
        console.log(i)
    }

    if(i == 0) {
        direction = 0;
    } else if(i == maxCount) {
        direction = 1;
    }
    setTimeout(countdown, 60);
}

countdown();

A directional variable is employed to monitor the counting direction.

Check out the Demo

Answer №2

@sachleens came up with an idea, resulting in a more concise code

let i = 0, max = 5, cnt = 1;
      const timer = function() {
        i += cnt;
        if (i>=max) {cnt = -1;}
        if (i===0)  {cnt = 1;}
        console.log(i);
        setTimeout(timer,60);
      }
timer();

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

Updating a specific field in a document using Node.js and MongoDB

Hey, I'm a beginner in nodeJS and I could use some help. I've been able to update an entire document easily but I'm struggling to update just a single value. Here's my code: router.patch("/:id", async (req, res) => { console.log(re ...

What is causing it to give me 'undefined' as the result?

Trying to execute a script, test.al(); and within test.al, it calls getcrypt.php();. The php script is hosted on a webserver, and it is functioning properly. Here are the current scripts being used: JS var getcrypt = { php: function () { $.a ...

Recalling the layout following the user's computer restart

I am creating a simple online editing tool (similar to Microsoft Outline) for coursework and I would like the outline details to be saved even if the user restarts the system. How can I achieve this? <html> <head> <title>Editor</ ...

The EJS template in an Express.js (Node.js) application is not updating to show recent modifications

I'm currently developing a node.js application that serves an index.ejs page through a route named index.js. var express = require('express'); var router = express.Router(); /* GET home page. */ router.get('/', function(req, res) ...

Creating Scroll Animations in Javascript - Mastering scrollIntoView Animation

When I click on a div, I was only able to bring it into view with the scrollIntoView function. It functions correctly and meets my expectations, but I am curious if there is a way to animate it and slow down the process. I attempted a suggestion found her ...

What steps are involved in developing an Angular library wrapper for a pre-existing Javascript library?

Imagine having a vanilla Javascript library that is commonly used on websites without any frameworks. How can you create an Angular library that can be easily installed via npm to seamlessly integrate the library into an Angular application? The process o ...

Ajax encountered a problem while attempting to download the file

I have a situation where JavaScript generates content within a function, and I need to save that content in my downloads folder. However, when I attempt to do so via AJAX, it does not work and no errors are being displayed. Here is the JS code: $.ajax({ ...

What is the best way to repurpose the vuex module for multiple components?

Currently, I am tackling the pagination aspect of a project that involves handling a large amount of data. My initial instinct was to store this data within Vuex. However, I ended up implementing all the logic in the Vuex store module. Now, my goal is to f ...

How can you use Firestore to filter documents based on their presence in another collection?

For instance, I am looking to retrieve all users who are members of a certain "space". Here is a simplified Firestore rule example: match /users/{userId} { allow read: if exists(/databases/$(database)/documents/spaces/SPACEID/members/$(userId)); } Java ...

Discover the process for finding a Youtube Channel Name with querySelectorAll

OUTPUT : Console URL : https://www.youtube.com/feed/trending?gl=IN document.querySelectorAll('a[class="yt-simple-endpoint style-scope yt-formatted-string"]')[0].innerText; document.querySelectorAll('a[class="yt-simple-endpoi ...

Is it possible to create a component in React without using JSX?

Is it possible to create a React component without using JSX? I'm trying to render a header element with nested h1 and h2 tags, but only the paragraph tag is showing up. Why is only the React element rendering and not the rest? I referred to a Codepe ...

Encountering a JavaScript runtime error while trying to access and interpret JSON

Currently, I'm facing a challenge with converting a C# list of string types into a JSON object. The issue arises when trying to read this JSON object later in JavaScript. On the other hand, the process seems to work fine when dealing with a C# list of ...

What causes the issue of the 'MERGE' statement in Node.js resulting in the creation of duplicate nodes in Neo4j?

Currently tackling a Node.js project involving the creation of nodes in Neo4j using the 'MERGE' statement. Despite employing 'MERGE' to prevent duplicate nodes, duplicates are still being generated at times. Extensive searches through ...

Unleashing the power of promises through chaining resolution and rejection

My function returns a deferred.promise, following jQuery's deferred concept. Regardless of the success of the file read, I want to move on to the next step in the chain. Here's an example of how I currently handle it: var a, b, c; readF ...

Having trouble with less.modifyVars not functioning properly in Visual Studio?

I attempted to dynamically change the LESS variable using HTML within an AngularJS function. The code worked fine on XAMPP with simple HTML and CSS, but when I transferred it to an enterprise app in Visual Studio, it stopped functioning properly. While the ...

Methods for bypassing a constructor in programming

I am working on a code where I need to define a class called programmer that inherits from the employee class. The employee class constructor should have 4 parameters, and the programmer class constructor needs to have 5 parameters - 4 from the employee c ...

Is it possible to enable password authentication on Firebase even if the user is currently using passwordless sign-on?

In my frontend JS project, I have integrated Firebase for web and am utilizing the passwordless (email link) authentication method for users. I am now interested in implementing password sign-on for an existing user who is currently using passwordless si ...

Filtering and searching within a diverse HTML table array

Looking to implement a filter feature in a table with a complex array structure: let items [ { "_resource":{ "values":[null, undefined, true, 'foobar', {'amount': 1111, 'isValid': true} , ...

What is the best way to customize multiselection in jqgrid?

jQuery("#grid").jqGrid({ datatype: "local", width:'auto', height: 'auto', multiselect:true, colNames:[ 'no' ], colModel:[ {name:'no', align:'r ...

Is it possible to track traffic using Alexa or SimilarWeb on a single-page application?

We are currently grappling with the challenge of how to effectively track traffic and user engagement within our classified sites on a single-page application built in angularJS. While we have successfully managed SEO and tracking with Google Analytics, we ...