Making a function to wait an event before returning?

江枫思渺然 提交于 2019-12-19 10:27:33

问题


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.


回答1:


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...




回答2:


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.




回答3:


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();
}


来源:https://stackoverflow.com/questions/8027392/making-a-function-to-wait-an-event-before-returning

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!