Js区间内的区间不工作

js interval inside interval not working

本文关键字:区间 工作 Js      更新时间:2023-09-26

我正试图建立一个游戏-目标是收集只有正确的对象,从浏览器的顶部。

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

问题是-当创建其他元素时(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/

我已经创建了一个新的小提琴https://jsfiddle.net/qkjounLb/

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

你可以从这里开始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);
});