Why is my code functioning perfectly when clicked or linked, but suddenly fails when a key is held down?

When the functions are called using LINK everything works smoothly:

function display() {
  let time = new Date();
  timer = setTimeout(function() {
    document.getElementById('output').innerHTML = time.getSeconds() + '.' + time.getMilliseconds();
    display();
  }, 150);
}

function stopDisplay() {
  clearTimeout(timer);
  document.getElementById('output').innerHTML = 'all stopped!';
}
<input type="search" name="sin" onkeypress="display();" onkeyup="stopDisplay();this.value='';" />

<a href="" onclick="display();return false;">show</a> /
<a href="" onclick="stopDisplay();return false;">not show</a>
<div id="output"></div>

It also works fine if you press a key only once.

But when the user holds down a key, then things go wrong.

Why is that?

Answer №1

It appears that the abundance of calls to the show() function is due to recursive calling, resulting in more instances of show() being executed compared to stopshow. This leads to numerous instances of setTimeout not being cleared. It raises the question of why there is a need to call show() again within the setTimeout? Alternatively, one could consider using clearTimeout right before making the subsequent call.

let M

function show() {
  s = new Date();
  clearTimeout(M)
  M = setTimeout(function() {
    document.getElementById('output').innerHTML = s.getSeconds() + '.' + s.getMilliseconds();
    // remove this line
    show();
  }, 150);
}

function stopshow() {
  clearTimeout(M);
  document.getElementById('output').innerHTML = 'all stopped!';
}
<input type="search" name="sin" onkeypress="show();" onkeyup="stopshow();this.value='';" />

<a href="" onclick="show();return false;">show</a> /
<a href="" onclick="stopshow();return false;">not show</a>
<div id="output"></div>

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

Looking for a way to execute code exclusively when the 'other' option is chosen? Let's tackle this challenge with Javascript and swig

I am looking to utilize swig (my chosen templating engine) for incorporating JavaScript code that will only display when the user selects the 'other' option from the select menu. <div class="form-group"> <select class="custom-select"&g ...

Decoding JavaScript content with Python

Currently, I am dissecting this specific portion of HTML <script type="text/javascript"> var spConfig = new Product.Config({"attributes":{"150":{"id":"150","code":"size_shoe","label":"Schuhgr\u00f6\u00dfe","options":[{"id":"494","label ...

Why must the sidebar be displayed horizontally on the smartphone screen?

I've been struggling to make the sidebar menu on my smartphone display horizontally with icons at the top and text at the bottom. I've tried using flex and other methods, but it still doesn't work sideways. Am I missing something? const s ...

Error encountered when attempting to update a user through a put request in Expressjs: CastError

When making a POST request to the API endpoint http://localhost:5000/api/notes/updatenote:id, where id represents a specific user ID, the goal is to update the notes associated with that user. The notes collection in MongoDB contains the notes with their o ...

What is the reason for Jquery targeting every single div element that has the class rule-name assigned to it?

I am new to JQuery and I'm taking it slow. In my Tampermonkey script, I have included the following line of code and executed it on the desired page. $('<span id="matrixVarTableInit">Default Rule Tests</span>').insertAfter( "div ...

Using an iframe to access HTTP content from an HTTPS website

Currently, I am facing an issue with a page that contains an iframe loading an HTML template from an Amazon AWS S3 bucket. Within the iframe, my goal is to take the link of the parent window and add additional parameters. For example, let's say my pa ...

Enhancing ASP.NET MVC 5 Application with jQuery Validate: Implementing Submit Button Click Events

In the process of developing an ASP.NET MVC 5 application, I find myself faced with a dilemma. The current setup involves using the jQuery Validate plug-in that comes packaged with MVC applications. Upon clicking the "submit" button, jQuery Validate kicks ...

Utilize a standard JavaScript function from a separate document within a function of a React component

I am facing an issue where I need to incorporate a standard JavaScript function within a React component function. The script tags are arranged in the footer in the following order: <script src="NORMAL JAVASCRIPT STUFF"></script> // function ...

What causes jquery-ui resizable to set the width of the div with the "alsoResize" property?

I have created a series of divs structured like this: <div id="body_container"> <div id="top_body"> </div> <div id="bottom_body"> </div> </div> Additionally, I have implemented the following funct ...

Using JavaScript, combine two arrays of varying lengths in an alternating fashion

Seeking a method to alternate between joining two arrays of different lengths. const array1 = ['a', 'b', 'c', 'd']; const array2 = [1, 2, 3, 4, 5, 6, 7, 8, 9]; const result = array1.reduce((arr, v, i) => arr.conc ...

Creating a dynamic search bar using Ajax with support for multiple keywords

I recently attempted to create an ajax search bar for my website. It functions perfectly with a single keyword, however, I'm facing some difficulty when trying to make it work with two keywords. I thought about parsing the data in the input field, but ...

Is it possible for me to automatically insert an event into the user's phone calendar through code?

Currently, I am working on developing a mobile website using Laravel 4 framework and regular jquery instead of jquery mobile. I'm curious to find out if it is possible to use code (javascript - jquery ... or a plugin) to insert an event into the user& ...

Tips for showcasing a collection of items in a React application using data from a database

My goal is to display a list of items from a database, filtered by the Id of the currently logged-in account on the application. To achieve this, I attempted to use a previous state with the account information and fetch only those items using the id in t ...

Transform the attribute of an object into numerical form

Is there a way to convert object properties that are integers from a string to an actual numerical type? I specifically need the following conversions: Convert Lat/Long to float type Transform Date properties into numbers This snippet showcases one obj ...

What is the most effective way to utilize forms in order to send information from both an input field and a dropdown selection menu with just one button click

Currently utilizing Material UI and React for my project. I am dealing with data from a text field and a drop down select that I want to be 'submitted' when a button is clicked https://i.sstatic.net/fvxo0.png Below is the code with unnecessary ...

There seems to be an issue with updating the ng-model properly in angular-ui-tinymce

I have encountered a problem where I am attempting to add a DOM node when a custom button is clicked, but the model associated with the textarea is not being properly updated. To illustrate the issue, I have created a plunker as a demo. [https://plnkr.co ...

What causes the consistent filling of responses in jQuery ajax?

After observing that the response of an ajax call using jQuery is never empty, I have come across the following code snippet: $.ajax({ type: "get", data: { data }, url: "phpFile", datatype: 'text' }).done(functio ...

Guide to Efficiently downloading a PDF file using Vue and Laravel

THE SCENARIO: Client Side: Vue. Server Side: Laravel. Within the web application, I need to enable users to download specific PDF files: I require Laravel to retrieve the file and send it back as a response to an API GET request. Then, in my Vue web ap ...

What is the best way to pass a dynamically generated component as the ng-content for another dynamically generated component?

Need help with creating a modal for our library using viewRef.createComponent. I want to generate Component A and embed Component B inside it, utilizing <ng-content> to fetch content from Component B. Component A serves as the modal template, while ...

Solving Problems with Inline Tables using Angular, Express, and Mongoose's PUT Method

For the past few days, I've been struggling to figure out why my PUT request in my angular/node train schedule application isn't functioning properly. Everything else - GET, POST, DELETE - is working fine, and I can successfully update using Post ...