How do I stop a function from running?

  • 0
    Here is the code:
    function getRandomNumber(size){
        return Math.floor(Math.random() * size);
    }
    
    function getDistance(event, target){
        var diffX = event.offsetX - target.x;
        var diffY = event.offsetY - target.y;
        return Math.sqrt((diffX * diffX) + (diffY * diffY));
    }
    
    function getDistanceHit(distance){
        if(distance < 10){
            return "Обожжешься!";
        }else if(distance < 20){
            return "Очень горячо!";
        }
        else if(distance < 40){
            return "Горячо!";
        }
        else if(distance < 80){
            return "Тепло!";
        }
        else if(distance < 160){
            return "Холодно!";
        }
        else if(distance < 320){
            return "Очень холодно!";
        }else{
            return "Замёрзнешь!";
        }
    }
    
    var width = 400;
    var height = 400;
    var clicks = 0;
    
    var target = {
        x: getRandomNumber(width),
        y: getRandomNumber(height)
    }
    
    function mapClick(event){
        clicks++;
        var distance = getDistance(event, target);
        var distanceHit = getDistanceHit(distance);
        $("#distance").text(distanceHit);
        if(distance < 8){
            alert("Клад найден! Сделано кликов: "+clicks);
        }
    }
    
    $("#map").click(mapClick);


    You need to set a limit on clicks, and if the user reaches this limit, the game ends. I tried to create the following block:
    if(clicks === 10){
            return false;
        }

    But nothing happened, the same story with break. Perhaps I somehow misused break and return, but nothing works, I need help.
    JavaScript Arianna Burgess, Aug 13, 2019

  • 1 Answers
  • 0
    It is not clear where you inserted the condition.



    It seems like there is nowhere to be easier:

    function mapClick(event){
    if( clicks > 10 ){
    alert( "Проиграл" );
    } else {
    clicks++;
    var distance = getDistance(event, target);
    var distanceHit = getDistanceHit(distance);
    $("#distance").text(distanceHit);
    if(distance < 8){
    alert("Клад найден! Сделано кликов: "+clicks);
    }
    }
    }
    Felix Bennett

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!