2

I want to set a hotkey to several functions by jquery hotkeys. And I need to check if a function is finished, may be something like:

if("function A is completed")
{
    "Ctrl+A is now set to function B"
}
else
{
    "Ctrl+A is set to function A"
}

How could I check this? Or any better ideas?

BradleyDotNET
  • 60,462
  • 10
  • 96
  • 117
Lewis
  • 14,132
  • 12
  • 66
  • 87

2 Answers2

2

JavaScript on web browsers is single-threaded (barring the use of web workers, and even with those a function can't be interrupted), so except for a couple of bugs in issues with Firefox, a function cannot be interrupted in the middle. So if your code is running, the other function is not, by definition.

(For details on the issues with Firefox, see this answer by bobince about some very edge-case scenarios.)

Community
  • 1
  • 1
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
1

Depending on the situation there are a couple of things you can do. You can call the function when you've finished completing the current function or you can set a boolean for the same thing.

function A(){
  alert('run items in function A');
  return fireNewFunctionWhenComplete()
}

or set a flag

/*global var*/
var functionBCompleted = false;

function B(){
  alert('run items in function B');
   return functionBCompleted = true;  
}

function testFunctionComplete(){
  if(functionBCompleted){
    alert('function B Copmleted');
  }
  else{
    alert('function B not run');
  }
}

This is a very simple example and as @T.J. mentioned you can't interrupt a running process. However, you may want to take a look into the promises spec if you want to run something when an asynchronous operation has completed.

Zanderi
  • 907
  • 9
  • 15