Search code examples
javascriptsetintervalanonymous-function

Calling Javascript anonymous function method on timer


I'm working on creating a fireworks show in javascript for my last day of work tomorrow and I'm having some trouble getting it to automate. I'm using the fireworks found here and it works great, but this is going to be on a status webpage that I developed a while ago so I want the fireworks to be automatic instead of on click.

I've created a function on the fireworks.js page that looks like this...

function fireFireworks(){
    var num = Math.floor(Math.random()*3) + 1;
    for(i=0;i<num;i++){
        createFirework();
    }
}

This will be used to fire between 1 and 3 fireworks when it's called. Then I setup

setInterval('fireFireworks()', 5000);

When both of these are defined in my local file and not in the fireworks.js file I get a bad reference to createFirework().

So I moved the fireFireworks() to just under the initialize function in fireworks.js and then I would get a bad reference to fireFireworks() so I moved my setInterval into the intialize function, but I still get a bad reference to fireFireworks().

However, if I change the binder for onmouseup from document.addEventListener('mouseup', createFireworks, true); to document.addEventListener('mouseup', fireFireworks, true);

It successfully creates my multiple fireworks.

I'm assuming that the scope of setInterval is playing a part here. If anyone could give me an idea of how I could automate this as well as some info as to why my setup isn't working I'd really appreciate it!


Solution

  • It's nicer to pass the function itself to setInterval, i.e.

    setInterval (fireFireworks, 5000)
    

    As for the scoping, if your createFireworks function isn't used anywhere else, just put it inside fireFireworks and you don't have to worry about it any more (it's generally considered nicer to do that anyway, because it avoids polluting the global scope).

    Otherwise, wrap both functions in a closure:

    (function ()
    {
        function fireFireworks ()
        {
            /* ... */
        }
    
        function createFirework ()
        {
            /* ... */
        }
    
        setInterval (fireFireworks, 5000)
    
    }) ();