tl;dr you need to wrap your IIFE with parentheses or to not use an IIFE at all.
Your use of generators is fine, and once you add the parens, everything works as normal.
Note that you don't really need a IIFE to run your code, but my answer below explains why what you have is not working.
Function declarations vs Function expressions
The main problem you have is in this code:
function() {
var gen = sogen();
gen.next(so);
gen.next(so);
}()
This will produce an error similar to:
Uncaught SyntaxError: Unexpected token (
The problem here is that you are trying to use a function declaration as a function expression.
From MDN (emphasis mine):
A function expression is very similar to and has almost the same syntax as a function statement (see function statement for details). The main difference between a function expression and a function statement is the function name, which can be omitted in function expressions to create anonymous functions. A function expression can be used as a IIFE (Immediately Invoked Function Expression) which runs as soon as it is defined. See also the chapter about functions for more information.
This means that in order to execute a function immediately, you need to use a function expression rather than a statement.
One common way of writing a function expression is to wrap the function in parentheses:
function a() { return 'a'; } // Function declaration
(function b() { return 'b'; }) // Function expression
To convert that into an IIFE, you can add the ()
invocation parens at the end:
(function c() { return 'c'; })() // IIFE
which calls the function immediately.
Note that I prefer to put the invocation parentheses inside the wrapping parens but this is just a stylistic choice and works in the same way:
(function c() { return 'c'; }()) // IIFE
Here's the code from the answer, plus the parens wrapping the IIFE:
function so() {
console.log('inside the timer');
}
function* sogen() {
const callback = yield;
setTimeout(callback, 2000);
return 1;
}
(function() {
const gen = sogen();
gen.next(so);
gen.next(so);
}())
Alternatively, simply remove your IIFE:
const gen = sogen();
gen.next(so);
gen.next(so);
or if you need a function declaration, call the function on the next line:
function run() {
const gen = sogen();
gen.next(so);
gen.next(so);
}
run();