Defeat a JavaScript function or turn it into a Singleton Function

Is there a method to stop a running JavaScript function?

Or is there a way to make sure that only one instance of the function runs at a time and any previous instances are removed upon restart?

For example, if I call:

_.defer(heavyDutyPaint);  //How can this be stopped when a second one is called?
_.defer(heavyDutyPaint);  

Currently, I assign a token to each function call. Only with the current token value can the function paint on the screen.

It looks something like this -

var token;

function heavyDutyPaint(){
     var localToken = Math.floor((Math.random()*10000)+1);
     token = localToken;

     // Perform a time-consuming read
     var results = getResults();

     if(token === localToken){
          paintScreen(results);
     }
}

function defer(method){
    setTimeout(method, 1);
}

defer(heavyDutyPaint);
defer(heavyDutyPaint);

Is this the only way to ensure that only the latest called function can access certain resources or services?

Additional Info: Regarding the getResults method, it makes some REST calls that should not happen more than once. There is separate logic in place to manage this. The method also performs certain calculations. I am not looking for a lock-based solution as suggested in an answer. I would like to know if there is a way to kill or halt execution somehow, or flag it. Ideally, I want the second function to execute its task instead of the first one. Think of these functions like filters - the most recently requested filter is the relevant one.

Answer №1

Consider implementing the following approach:

const performHeavyTask = (function() {
  let isRunning = false;
  return function() {
    if(!isRunning) {
      isRunning = true;
      requestAnimationFrame(function() {
        // actual task execution happens here
        isRunning = false;
      });
    }
  };
})();
performHeavyTask();
performHeavyTask(); // this second call will be ignored

In this code snippet, a isRunning variable is enclosed within the heavy task function to prevent concurrent calls while a previous call is still in progress. However, for optimal performance, heavy tasks are usually executed using synchronous callbacks to maximize the efficiency of the JavaScript thread.

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

The global variable is inaccessible when invoked within a dynamically generated function

The variable selected is a global one and accessed using this.selected, which reliably returns the correct value. However, when called from a dynamically created function, it returns unknown. onClick: function(val){ for (i = 0; i < positi ...

Utilize this JavaScript tool to effortlessly transform an XML string into JSON format

Looking for the optimal javascript function, plugin, or library to effectively transform an XML string into JSON format. One tool I came across is , but unfortunately, it struggles with strings that begin with 0. For example, 005321 may end up converted t ...

Proportional fluid image grid with responsive design

After implementing various media queries, I've managed to create an image grid using Bootstrap 4+ that looks great on specific devices and layouts. Here's the reference code: .cmd-three-img-container { position: relative; margi ...

What is the process for choosing an element, wrapping it in a <div>, and appending a class to it using only JavaScript?

When constructing a responsive website, all CMS entries are in markdown. It's not feasible to manually code the div into each new entry, so dynamic class addition is necessary. The task at hand involves selecting an <img> within a post and wrap ...

Launching event handlers and applying CSS classes within a single scenario

How can I toggle the visibility of a button based on form field validation in JavaScript? I want to show or hide the button when the .confirm button is clicked, and if the form is valid, add a checkmark to the body element through event listener. The issu ...

Guide on displaying multiple views along with their respective models fetched through AJAX in Backbone

Hey there! I'm currently working on painting a screen with multiple models and associated views in backbone. To achieve this, I have separate ajax calls to fetch data for these views. Initially, I thought using the jQuery function $when(ajaxcall1, aja ...

Choose the dropdown item depending on the related text

I am currently working on a drop-down menu where each option has a value and associated text. The selected option is then displayed row by row in a table, with an edit button next to each row that allows the user to change the selection. I am trying to imp ...

The Alphavantage was acting strangely when I ran a Google script

After following a tutorial video on YouTube, I was confident that my Google script for Google Sheets was working perfectly. However, I encountered two strange issues that I just can't seem to figure out. The code below is exactly what I need - it ...

Having trouble with processing the binding? Use ko.mapping.fromJS to push JSON data into an ObservableArray

Hey everyone, I'm struggling with my code and could really use some help. I'm new to knockout and encountering an issue. Initially, I receive JSON data from the database and it works fine. However, when I click 'Add some', I'm tryi ...

What is the best way to neatly import multiple images in Next.js?

I have a dilemma involving 10 images located in my public directory that I need to use in a component. Instead of individually importing each image like this: import imgurl1 from "../../public/celsius.gif"; import imgurl2 from "../../public/ ...

Building a hybrid application in Angular using UpgradeModule to manage controllers

I am currently in the process of upgrading a large AngularJS application using UpgradeModule to enable running AngularJS and Angular 6 simultaneously without going through the preparation phase, which typically involves following the AngularJS style guide. ...

Tips for managing image uploads while incorporating pre-set error detection into a form

I'm facing a challenge with integrating an optional image upload feature into my express app. The issue seems to be related to the way I've structured the app, as it appears to be trying to pass the image name from the body instead of utilizing t ...

Using Array Data Binding in SAPUI5 for Lists

I am looking to connect a list along with its content to a model. var listItem = new sap.m.StandardListItem({ title: "{carDataModel>/cars/1/carId}", }); var list = new sap.m.List("carList", { }); list.bindItems('carDataM ...

Lambda script for Amazon Alexa Skill is not functioning as expected

I am currently developing a Lambda function for an Amazon Alexa skill using NodeJS. For those unfamiliar, Alexa is a cylindrical speaker that responds to voice commands, and a "skill" is essentially a voice-operated app for the device. This particular func ...

What is the best way to enhance a state's capabilities in Machina.js?

When using Machina.js (version 0.3.6), how can I instantiate a modified FSM constructor where both the child and parent FSMs define behaviors in the same states? Here is the code snippet: var _ = require('lodash'); var machina = require('m ...

Is there a way to retrieve the JSON url from the input box

My goal is to retrieve a JSON file from a URL entered in a text box. I have identified the text box as txtr and used jQuery to get the value like this: var txtbval = $("#txtr").val();. I then included this value in the JSON parsing script as follows: url: ...

Is there a way for me to show "No data" when the json response in vue js is empty?

Is it possible to display a message like "No search results" when there is no data available? I am new to this and only have basic understanding. Can someone guide me on how to achieve this? Example of my JSON data when it's empty: { "status": true ...

What is the most effective method for incorporating CSS using Javascript to target a specific aria-label attribute?

Is there a way to add a CSS property to a specific tag with a particular aria-label on document load? My goal is to change the flex order of a section to 2. I need help using JavaScript to target the aria-label 'block 1' so I can set the order t ...

Illuminate a corresponding regular expression within a text input

I currently have a functional code for testing regex, which highlights matching patterns. However, my challenge lies in highlighting the result within the same input as the test string. Below you will see the HTML and JavaScript snippets along with two ima ...

developing a cheat prevention system for an internet-based multiplayer game

I am facing an issue with my website that includes a simple game and a basic scoreboard feature using express. Whenever a player dies in the game, their score is sent to the server via a post request and added to the leaderboard. The problem I'm encou ...