I find the SetInterval loop to be quite perplexing

HTML

<div id="backspace" ng-click="deleteString(''); decrementCursor();">

JS

<script>
    $scope.deleteString = function() {
        if($scope.cursorPosVal > 0){
            //$scope.name = $scope.name - letter;
            $scope.name = [$scope.name.slice(0, $scope.cursorPosVal - 1) + $scope.name.slice($scope.cursorPosVal)].join('');
            console.log($scope.name);
            setTimeout(function(){ setCaretPosition("inputBox", $scope.cursorPosVal); }, 30)
        } else {
            $scope.cursorPosVal = 1;
        }
    };
</script>

I am in the process of developing an on-screen touchscreen keyboard. My current focus is on the backspace button functionality. I aim to implement a feature where holding down the backspace button will automatically delete characters. To achieve this, I need to incorporate setInterval into my codebase, which presents a new challenge for me.

Answer №1

It seems like you're looking to have a function repeat itself while a button is kept pressed.

Using setInterval() is the right way to go, but you might need to adjust how you handle the event.

You can refer to this simple example on JSFiddle for a clearer understanding:

http://jsfiddle.net/daq9atdd/1/

$(function(){
    var interval = null;

    $('#myButton').mousedown(function(){
        interval = setInterval(function(){
            console.log('Hello !');
        }, 250);
    });

    $('#myButton').mouseup(function(){
        clearInterval(interval);
    });
});

In this code snippet, the interval starts when the button is pressed, pauses it and resets it once the button is released.

Answer №2

You seem confident in your use of setInterval.

In the event that the browser experiences a brief hang (such as due to a background task), setInterval will continue queuing backspace calls until it regains CPU time. This could result in the user not seeing any immediate changes and holding the backspace key longer than necessary, leading to a sudden removal of multiple characters when the browser resumes normal operation.

By implementing a timeout after each call, you ensure that the user does not inadvertently delete more characters than intended. This can be crucial for enhancing the overall user experience.

Check out this example using AngularJS directives and setTimeout

For further reference:

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

Create dynamic automatic titles in HTML with JavaScript

Below is the code snippet to add an image with a link to the home-page and an h1 with the document name (if there isn't one already). This HTML code includes a JavaScript file reference in the <head> section and uses a <h1> tag for the ti ...

How can CSS be utilized to style the visited links that are hovered over

Is there a way to change the font color specifically for visited hyperlinks that are being hovered over by the mouse? I am trying to achieve this: a:visited:hover {color: red} ...

Can a new EJS file be generated using the existing file as a template?

I am in the process of building a website navbar and I am curious about how to automatically inject code from one ejs file into another ejs file. In Python's Flask framework, this is accomplished using the principle of {% block title%} and in another ...

Struggling to connect HTML elements with AngularJS and TinyMCE?

My objective is to edit text using tinymce, persist it in a database, and display it within a div by incorporating angularJS for the same styling and formatting. I am utilizing tinymce 3.5.8 with an angularUI directive. I have successfully saved the wysiw ...

Having trouble understanding why getStaticProps function is not loading before the main exported function

When I use npm run dev to troubleshoot this issue, it utilizes getStaticProps to process various d3 properties before injecting them into the main output function during runtime. However, it seems that getStaticProps is not running as expected - a consol ...

How can I efficiently fetch data from Firebase, manipulate it through computations, and present it using React Hooks?

I am currently working on retrieving multiple "game" objects from Firebase Storage, performing statistical calculations on them, and then presenting the game statistics in a table. Here is an overview of my code structure: function calculateTeamStatistics( ...

What is the best way to transform HeadersInit into an Object<string,string> data type?

In short, I am faced with the task of converting the headers of a RequestInit into a format that another library can comprehend. This particular library requires the headers to be in the format of Object<string, string>. Initially, I attempted someth ...

Rotation of Weekly Menus

I have a project to enhance our Menu Order Website by adding a weekly rotating menu feature. I have completed the entire website, including the admin panels, but I am struggling to implement the rotating menu functionality. Currently, all menus are include ...

Removing nested divs using JavaScript

My website has a nested div structure which contains multiple child divs. Here is an example of the div structure: <div id="outside-one"> <div class="inside" id="1"></div> <div class="inside" id="2"></div> <div ...

Tips for ensuring that Breadcrumbs are displayed properly with the noWrap feature

I am currently working on making the MUI component Breadcrumbs responsive. The issue I am facing is that when the Breadcrumbs component fills up all available space, the items shrink and use ellipsis like a Typography component with the noWrap property se ...

Adding Node Modules during the setup of an ElectronJS application

Hey there! I'm currently working on an ElectronJS application designed for developers. One of the key features is checking for the presence of NodeJS on the user's computer. If it's not detected, the app will automatically download and insta ...

Anticipating outcome: row 1 column 1 (character 0) in Python

As a newcomer to the world of Python, I am currently attempting to parse data in my application using the following lines of code: json_str = request.body.decode('utf-8') py_str = json.loads(json_str) Unfortunately, when I reach this line (jso ...

Breaking free of the constraints of a 100% height container, UL escapes its

In both Chrome and Firefox, UL list items do not seem to adhere to the parent container's width of 100%. I attempted to use list-style-position: inside;, but unfortunately, that did not solve the issue: <html style="height: 100%"> <body styl ...

Experiencing difficulties launching my Server.JS due to a listening error

Hey there, I'm struggling to get my server.js up and running. Whenever I try to run node on it, I keep getting the error message "listening on *:3000". Below is the code for my server.js: var app = require('express')(); var http = require(&a ...

Having trouble configuring bcryptjs in a React.js project

I have been working on setting up a single registration page within a react component. However, I encountered an issue when trying to hash the password before sending the response to my back-end. I am puzzled as to why the code snippet below is not functi ...

AngularJS dynamic and wildcard routing strategy is a powerful feature that allows for flexible and customizable navigation within web applications

Currently, I have implemented angular ui router as shown below: angular .module('app', [ 'ui.router' ]) .config(['$urlRouterProvider', '$stateProvider', function($urlRouterProvider, $stateProvider) { $u ...

AngularJS uses variables defined by using curly braces like {{"message"}}

I am currently utilizing the following code snippet to monitor route changes: $scope.$on('$routeChangeStart', function (event, toState, toParams, fromState, fromParams) { //content $log.log(toState); } Whenever I print out "toState ...

Tips for extracting text from a multiline tag using Selenium

I need help extracting the text "1 file has been successfully uploaded" from the code snippet below: <div class="formbuttons"> <h3 id="res" class="demo" style="color: rgb(255, 255, 255); display: block;"> <center>1 file <br>has bee ...

When using the GET method to load a PHP file via AJAX, the page may not display certain jQuery plugins even after the file

Hello, I am a beginner learning AJAX and JQuery. Maybe this is a silly question, but please bear with me. I am trying to dynamically show data without refreshing the page using AJAX. I have a function loaded in the body tag which handles this. Everything ...

Issue with VueJS instance: Unable to prevent default behavior of an event

Is there a way to disable form submission when the enter key is pressed? Take a look at the different methods I've attempted along with the code and demo example provided below. SEE PROBLEM DEMO HERE Intended outcome: When you focus on the input, pr ...