间隔内的js间隔不起作用

js interval inside interval not working

我正在尝试构建一个游戏 - 目标是只收集从浏览器顶部掉落的正确对象。

我创建了一个调用函数的间隔,该函数每 5 秒创建一个新元素,并且在该函数内部我创建了另一个间隔来检查元素是否到达底部。

问题是 - 当创建其他元素时(5 秒后)检查器间隔停止检查当前元素并开始检查新元素 - 所以它永远不会到达底部。

代码如下:

    var newDrop =function(){
    random = Math.random();
    randNum = Math.floor(foodsImages.length * Math.random());
    drop = $('<img class="drop" src="'+ foodsImages[randNum].img +'">').appendTo('.board');
    drop.css({ top:0 - drop.height(), left: random * ($(window).width() - drop.width())});
    drop.animate({
        top: $('.board').height()
    }, 15000, function(){
        $(this).remove()
    });
    checkStop = setInterval(function(){new basket(drop, foodsImages[randNum])} , 30);
    drop.attr('interval', checkStop);
};

var basket = function(elm,obj){
    console.log(elm.offset().top + elm.height() > $('.basket').offset().top);
    if (elm.offset().top + elm.height() > $('.basket').offset().top){ //reached to the end
        leftLarger = elm.offset().left <= $('.basket').offset().left; 
        rightSmaller = elm.offset().left + elm.width() >= $('.basket').offset().left + $('.basket').width();

        if ( leftLarger && rightSmaller) { //if its been catched

            if (obj.value == true) { //and its a good thing
                console.log("yyah");
            }else{ // if its a bad thing
                console.log("bozzz");
            };

        }else{ //wasnt cathced

            if (obj.value == true) { //and suposed to cach
                console.log("bozzz");
            }else{
                console.log("msg");             
            };
        };

        elm.remove();
        return clearInterval( elm.checkStop ); //stop tracking
    };
}

$(function(){
    //handle drag movment
    $('.board').height( $(window).height() - $('header').height() );
    $('.basket').draggable({ 
        axis: "x",
        containment: "parent",
        scroll: false
    });

    //handle keypress on computers
    $(document).on("keydown", function (e) {
        var currentpost = $('.basket').offset().left;
        switch(e.which) {
            case 39:
                if ( (currentpost + $('.basket').width() ) < $(window).width()){
                    $('.basket').css('left', currentpost + 10);
                }
                break;
            case 37:
                if (currentpost - 10 > 0 ){
                    $('.basket').css('left', currentpost - 10);
                }
                break;
            default:
                return false;
        }
    });

    //objects
    foodsImages = [
        {
            "name": "adashim",
            "img" : "http://www.bulbsort.com/puzzlingapples/img/icon256x256.png",
            "value": true
        },
        {
            "name": "adom",
            "img" : "http://vignette1.wikia.nocookie.net/clubpenguin/images/8/86/Tacos_Puffle_Food.png/revision/latest?cb=20130820230847",
            "value": false
        },
        {
            "name": "tavshil",
            "img" : "https://tonytimecp.files.wordpress.com/2011/12/coin.png",
            "value": true
        },
        {
            "name": "pasta",
            "img" : "http://upload.wikimedia.org/wikipedia/commons/1/19/Food_Barnstar_Hires.png",
            "value": false
        }
    ];

    newDrop();
    addDrop = setInterval( function(){ newDrop() } , 5000);
});

这是演示:https://jsfiddle.net/12345/4rgxqdLp/2/

我创建了一个新的fiddlehttps://jsfiddle.net/qkjounLb/

您需要了解如何正确使用关键字 new 和 this。有了这种理解,OO 和作用域和闭包就会有所帮助。虽然不是必需的,但在这种情况下,了解作用域以及如何操作作用域可以快速解决问题。我不知道你的游戏程序的其余部分的范围,所以可能用这个关键字太过分了,但说明了要点 none the less。

您可以从这里开始 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures,但是有很多文章可以通过搜索了解 JavaScript 中的范围。

var betterDrop = function(foodsImages){
    this.random = Math.random();
    this.randNum = Math.floor(foodsImages.length * Math.random());

    this.drop = $('<img class="drop" src="'+ foodsImages[this.randNum].img +'">').appendTo('.board');
    this.drop.css({ top:0 - this.drop.height(), left: this.random * ($(window).width() - this.drop.width())});
    this.drop.animate({
        top: $('.board').height()
    }, 15000, function(){
        $(this).remove()
    });

    var scope = this;

    this.checkStop = setInterval(function(){new basket(scope.drop, foodsImages[scope.randNum])} , 30);
    this.drop.attr('interval', scope.checkStop);
}

var basket = function(elm,obj){
    console.log(elm.offset().top + elm.height() > $('.basket').offset().top);
    if (elm.offset().top + elm.height() > $('.basket').offset().top){ //reached to the end
        leftLarger = elm.offset().left <= $('.basket').offset().left; 
        rightSmaller = elm.offset().left + elm.width() >= $('.basket').offset().left + $('.basket').width();

        if ( leftLarger && rightSmaller) { //if its been catched

            if (obj.value == true) { //and its a good thing
                console.log("yyah");
            }else{ // if its a bad thing
                console.log("bozzz");
            };

        }else{ //wasnt cathced

            if (obj.value == true) { //and suposed to cach
                console.log("bozzz");
            }else{
                console.log("msg");             
            };
        };

        elm.remove();
        return clearInterval( elm.checkStop ); //stop tracking
    };
}

$(function(){
    //handle drag movment
    $('.board').height( $(window).height() - $('header').height() );
    $('.basket').draggable({ 
        axis: "x",
        containment: "parent",
        scroll: false
    });

    //handle keypress on computers
    $(document).on("keydown", function (e) {
        var currentpost = $('.basket').offset().left;
        switch(e.which) {
            case 39:
                if ( (currentpost + $('.basket').width() ) < $(window).width()){
                    $('.basket').css('left', currentpost + 10);
                }
                break;
            case 37:
                if (currentpost - 10 > 0 ){
                    $('.basket').css('left', currentpost - 10);
                }
                break;
            default:
                return false;
        }
    });

    //objects
    foodsImages = [
        {
            "name": "adashim",
            "img" : "http://www.bulbsort.com/puzzlingapples/img/icon256x256.png",
            "value": true
        },
        {
            "name": "adom",
            "img" : "http://vignette1.wikia.nocookie.net/clubpenguin/images/8/86/Tacos_Puffle_Food.png/revision/latest?cb=20130820230847",
            "value": false
        },
        {
            "name": "tavshil",
            "img" : "https://tonytimecp.files.wordpress.com/2011/12/coin.png",
            "value": true
        },
        {
            "name": "pasta",
            "img" : "http://upload.wikimedia.org/wikipedia/commons/1/19/Food_Barnstar_Hires.png",
            "value": false
        }
    ];

    new betterDrop(foodsImages);


addDrop = setInterval( function(){ new betterDrop(foodsImages) } , 5000);
});