Question

Why this script does not work correctly (freezes sometimes)?

var period = 600;

function Boom(){  
    var timeBoom = window.setInterval(function() {  
        if (period > 300) {  
            period = 300;  
            setTimeout(function () {  
                period = 600;  
            }, 1000);  
        } else {  
            period = 600;  
        }  
    }, 5000);       
}

function Shake() {  
    this.draw = function() {   
        setTimeout(function () {  
            Boom()  
        }, 5000)    
    };  
}

I need to just every 5 seconds the function Boom() was called, but the variable should be changed back again after executing (var period = 600).

Was it helpful?

Solution

ok mate, basically you need to get rid of all the un needed timing stuff.

first of all, a brief explanation:

setTimeout (func, x) will execute function func after x milliseconds.

setInterval (func, x) will execute function func Each x milliseconds.

so you only need to set interval one time, and let it work. i have corrected your code:

var period = 600;

function Boom() {

    if (period != 300) {
        period = 300;
    } else {
        period = 600;
    }

}

function Shake() {
    this.draw = function () {
        var time = new Date().getTime();
        var shakeX = (Math.sin(time * 2.0 * Math.PI / period) + 0);
        this.x = shakeX;
        var shakeY = (Math.sin(time * 2.0 * Math.PI / period) + 0);
        this.y = shakeY;
        this.context.drawImage(image, 0, 0);
        this.context.translate(this.x, this.y);
        setInterval(Boom, 5000)
    };
}

OTHER TIPS

John Resig -- creator of jQuery -- has a very nice piece on javascript timers.

Basically, becuse javascript is single-threaded, setInterval is not guaranteed to fire on every interval -- it will miss a beat if the js engine is busy at a particular cycle.

setTimeout will always call, but there could be an extra delay if another piece of code is queued up already when the time expires -- that is, the wait is potentially longer than the number of milliseconds you passed in as the second argument.

I'm guessing some of your setTimeout code might be getting in the way of one of the setInterval loops, but that's just a guess.

If that's the issue, try naming the anonymous fn you passed into setInterval, and then pass it into setTimeout instead, with 5000 ms wait, and another call (recursive) to the same function at when the interval expires.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top