简体   繁体   中英

Javascript function is working on firefox only once

I have the following javascript function:

function kitemoving() {
    setInterval(function(){
        kite.animate({
            top: '+=30'
        },{ 
            duration: 1500 
        });
        kite.animate({
            top: '-=30'
        },{ 
            duration: 1500
        });
    });
}
kitemoving();

Here is the Fiddle

Everywhere it is working fine only on Mozilla Firefox all the movements with this code are being worked only once. Could you help me to understand why?

Don't use interval, you could easily saturate the fx queue. Instead, use any complete animation callback, eg:

var kite = jQuery('.kite');

function kitemoving() {
    kite.animate({
        top: '+=30'
    }, {
        duration: 1500
    });
    kite.animate({
        top: '-=30'
    }, {
        duration: 1500
    }).promise().done(kitemoving);
}
kitemoving();

-jsFiddle-

You have to specify a value for the delay parameter.

setInterval expects at least two parameters. Quoting from MDN

func is the function you want to be called repeatedly.

delay is the number of milliseconds (thousandths of a second) that the setInterval() function should wait before each call to func. As with setTimeout, there is a minimum delay enforced.

param1, param2, and so forth, are additional parameters that are passed through to the function specified by func.

Therefore when you omit the second parameter you can not expect a defined behaviour.

All you have to do in order to make your fiddle work in Firefox, is provide an interval amount to the setInterval call

setInterval(function(){
    ....
}, 3000);

Here is an updated fiddle, which works in Firefox: http://jsfiddle.net/wdodmvyu/5/

You did not specify an interval value that is why Gecko is struggling.

function kitemoving() {
    setInterval(function(){
        kite.animate({
            top: '+=30'
        },{ 
            duration: 1500 
        });
        kite.animate({
            top: '-=30'
        },{ 
            duration: 1500
        });
    },300);//interval
}
kitemoving();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM