Trigger the function when the keyboard event is deactivated

Is there a way to continuously run the top set interval whenever I lift my finger from the space key? When I try using the key up event, it only executes that function once. I'm not sure how to implement if/else logic when adding an event listener.

setInterval(function (e) {
  r--;
}, 10);

document.addEventListener("keydown", function (e) {
  console.log(r);
  if (e.keyCode === 32) {
    setInterval(function (e) {
      r++;
      if (r > 240) {
        r = 200;
      }
    }, 100);
  }
});

Answer №1

If you're looking to execute a function a specific number of times when the space key is pressed, check out the code snippet provided below. This example will run a function 100 times.

var isExecuting = false;
var counter = 0;

function repeatFunction(func, times) {
    func();
    times && --times && repeatFunction(func, times);
}

function myFunction(){
    counter++;
    if(counter > 240){
        counter = 200;
    }
}

function onPressKey(e){
    if (!isExecuting && e.keyCode === 32) {
      isExecuting = true;
      console.log(counter);
      repeatFunction(myFunction, 100);
      isExecuting = false;
    }
}
document.addEventListener("keydown", onPressKey);

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

RetrieveByUserIdentifier as a callback method (express)

Can you help me refactor the code below to use a callback function instead? I want to ensure that the Req and Res logic is handled separately. Userservice.js function getByUserId(req, res, next) { let userIDD = req.body.userID; User.findOne({ use ...

How can I achieve a smooth opacity transition without using jQuery?

Although I understand that JQuery offers functions for this purpose, I am interested in finding a solution using only pure javascript. Is there a way to change the CSS opacity setting over time? Perhaps utilizing a unix time stamp with millisecond precisi ...

Rendering a dynamic list of asynchronous components in Vue 3, with support for extension

Could you please assist me in resolving this issue? I've spent countless hours searching for a solution, but I can't seem to make it work. Vue is still very new to me. Let me provide some more context. I have an asynchronous component that i ...

Utilize Node.js to proxy Angular requests to a service hosted on Azurewebsites

I am trying to set up a proxy post request in my Node.js server and receive a response from the target of this request. Below is an excerpt from my server.js file code where I have implemented the proxy, but I am facing a issue with not receiving any respo ...

Is there a way to make the onKeyDown event function properly in Next.js/React?

I'm currently developing a website with Next.js and am facing an issue trying to execute a simple function when a key is pressed. Strangely, the onKeyDown event isn't getting triggered as expected in my code snippet: <main onKeyDown={e => c ...

What are the potential drawbacks of combining the useState hook with Context API in React.js?

Within my code, I establish a context and a provider in the following manner. Utilizing useState() within the provider enables me to manage state while also implementing functions passed as an object to easily destructure elements needed in child component ...

I don't understand why this error keeps popping up. It seems that there are several `InputBase` components nested within a

Issue: The error message indicates that there are multiple instances of the InputBase component within a FormControl, causing visual inconsistencies. Only one InputBase should be used. I have tried enclosing my forms within the FormControl, but the error ...

Error occurs when page rendering is stuck in a recursive loop: Excessive re-renders detected

My webpage contains several form components as listed below. While everything on the front end seems to be working fine, I noticed that the Fetchmovies function is being called repeatedly and an error is thrown in the console: caught Error: Too many re-ren ...

"Utilizing d3 to parse and track variables within JSON data

To calculate the number of occurrences of s1, s2, and s0 in JSON data and use this information to plot a multiline chart with date (path of date is as follows reviews_details>>variable vf of JSON) on the X-axis versus the number of reviews (s1/s0/s2 ...

Sorting through an array of JavaScript objects and aggregating the step values for matching user names

Currently, I am delving into JavaScript and facing a certain challenge that may be considered easier for seasoned developers. My goal is to iterate through an array of objects, filter out objects with the same userName, and then aggregate their steps. The ...

What is the best way to implement form fields that have varying validation patterns based on different conditions?

Currently, my focus is on developing a form that prompts the user to choose between "USA" or "International" via radio buttons. The input field for telephone numbers should then adapt its requirements based on the selected country - either a 10-digit US nu ...

Discovering the following solution in JavaScript

I am a beginner in the field of web development and seeking help in generating a specific output for a given problem: var totalRows = 5; var result = ''; for (var i = 1; i <= totalRows; i++) { for (var j = 1; j <= i; j++) { res ...

Experience the mesmerizing motion of a D3.js Bar Chart as it ascends from the bottom to the top. Feel free to

Here is the snippet of code I am working with. Please check the link for the output graph demonstration. [Click here to view the output graph demo][1] (The current animation in the output is from top to bottom) I want to animate the bars from Bottom to ...

Receiving null value with Web API POST using [FromBody]

Below is the code for my WebAPI in C#: [Route("")] [HttpPost] public void SaveTestRun([FromBody] object data) { inputResultsToDatabase(data); } This is the ajax request I am making: sendTestData() { t ...

Here is a way to display the chosen option from a list using Angular Js

Seeking guidance on Angular.Js - I have a dropdown that successfully picks the selected data, but fails to display the selected value upon revisit. Is there a specific property I should set for this functionality? Snippet of my code: <select class=& ...

The process of sharing information between JavaScript classes

I'm struggling to grasp the concept of object-oriented JavaScript, particularly in terms of how classes can communicate with each other. Let's consider an example using Babel: We have a "ColorPalette" class that contains a list of colors We also ...

Send Summernote code data using Ajax to PHP which will then store it in the database

I have implemented a Summernote editor on a page where users can input content. When a user submits the page, I use jQuery to retrieve the HTML code from the editor and then send it to a PHP script for insertion into a database. The HTML retrieved before s ...

How can we efficiently iterate through an array in Node.js while making asynchronous calls?

I need to iterate through an array, pushing a new Thing to a list in the process. The Thing itself performs asynchronous calls. However, I am facing an issue where my for loop is synchronous but the new Things are asynchronous, causing the callback to be c ...

AJAX/PHP causing delays due to lag problems

I've been trying to implement an asynchronous call in my PHP script, but I keep running into the same issue: "Maximum call stack size exceeded." This is causing severe lag on my site and I suspect there might be a loop somewhere in my code that I just ...

An error was encountered while linting /app/layout.tsx at line 16: Rule "@typescript-eslint/no-empty-function" was violated due to inability to read properties of undefined (reading 'getTokens')

I am puzzled as to why the function that generates JSX is being checked by the "next lint" script with the rule "@typescript-eslint/no-empty-function". The code snippet at line 16 of the layout.tsx file looks like this: export default function RootLayout( ...