-1

I'm making a maze generator.
my code is something like this:

function generate() {
    //generate one iteration of a maze
}
function createmaze() {
    interval = window.setInterval(function() {
        //create the maze by calling generate repeatedly, and some other stuff (which works!)
        if(stop condition) {
            draw(maze);
            return(maze);
            window.clearInterval(interval);
        }
    }, 0);
}

alert(createmaze());

function draw() {
    //draws maze
}

my problem is, while the draw function runs fine and draws the maze it is supposed to, but createmaze returns undefined. it wouldn't be a problem, except i need the maze for some more code that won't draw it.
edit: i know i was using setinterval wrong with 0, but somehow things still worked

  • 1
    @charlietfl - He expects the interval to return the value. – Travis J Oct 04 '16 at 20:51
  • 2
    You're not returning anything in createmaze. You're creating a timer that runs every 0ms. Returning in that anonymous function won't be caught. – Dave Chen Oct 04 '16 at 20:51
  • Why are you using an interval of `0`? – tymeJV Oct 04 '16 at 20:52
  • One idea is to pass createmaze a callback, then when the stop condition is met, run the callback that was past to it. – Dave Chen Oct 04 '16 at 20:54
  • `stop condition` is not valid javascript lol.. also, you're returning beofer the interval is cleared, so it will never be cleared.. – Robert Parham Oct 04 '16 at 20:55
  • For starters, you have a syntax error on line 10. You never close your `if` block `}`. Also, `setInterval` is an async function, so it's not going to return the value you want. Additionally, most browsers don't support any value less than `4` for `setInterval`. Even if you set it to `0` it won't occur sychronously. One final note, if you need to manage async operations consider using the `Promise` interface... – War10ck Oct 04 '16 at 20:55
  • 1
    sorry, 'stop condition' is just a placeholder. obviously, i have a valid statement there in the real code, but i didnt put it in also, i dont have any syntax errors in the real code :/ – yayforfood Oct 04 '16 at 21:03

1 Answers1

1

The problem here is that your interval finishes in 4 milliseconds, that is the fastest that a browser will be able to execute the delayed task.

Moreover, returning a value from the interval is not captured, and as a result the createmaze() function itself has no return value. That is the reason you see undefined coming from it.

You need to either start using promises, or use a callback structure, in order to catch the asynchronous nature of your interval result.

Travis J
  • 81,153
  • 41
  • 202
  • 273