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.