2
function myFunction() {
    wait(); //what I put there?
    return;
}

myFunction(); 

//this is an event; when its triggered I want function to resume
onSomething = function() {
    myFunction.resume(); //what I put there?
}

Its just a local experience. Note that while(!resume) won't work because that would prevent the event onSomething to happen.

MaiaVictor
  • 51,090
  • 44
  • 144
  • 286
  • You can do that with [generators](https://developer.mozilla.org/en/JavaScript/Guide/Iterators_and_Generators), but that's not cross-browser. It will come with ECMAScript 6 though... – Šime Vidas Nov 06 '11 at 13:51

3 Answers3

5

This is not possible.

Instead of waiting for the event, you want to put whatever you need to do when it happens into the onSomething function.

Pekka
  • 442,112
  • 142
  • 972
  • 1,088
  • This is indeed not possible on javascript and I realized it is not necessary too. – MaiaVictor Feb 11 '12 at 02:09
  • Here's a situation where such a feature is necessary: A function that captures `oncontextmenu` event, and needs to return true or false based on a mouse event. The browser contextmenu cannot be triggered programmatically. – automaton Mar 13 '15 at 10:12
  • @automaton how do you mean "based on a mouse event"? When would that mouse event take place if the user is currently in the context menu? – Pekka Mar 13 '15 at 16:16
4

You have to switch your brains to thinking in events instead of the "traditional" programming flow. The way to do this is:

function myFunctionPart1() {
    doSomething();
}

function myFunctionPart2() {
    doSomethingElse();
}

myFunctionPart1();

onSomething = function() {
    myFunctionPart2();
}
JJJ
  • 32,902
  • 20
  • 89
  • 102
2

So, with a generator it would look like so:

function test() {
    // first part of function
    yield;
    // second part of function
    yield;
}

var gen = test(); // creating a generator

gen.next(); // execute first part

button.onclick = function () {
    gen.next(); // execute second part on button click
};

Live demo: http://jsfiddle.net/MQ9PT/

This however doesn't work beyond Firefox. It will become part of the ECMAScript standard in the next edition...

Šime Vidas
  • 182,163
  • 62
  • 281
  • 385