S
S
SightLS2022-04-22 00:40:33
JavaScript
SightLS, 2022-04-22 00:40:33

How to stop a JS function after executing a nested function?

Good afternoon/morning/evening/night!
There is a drag and drop function. It is necessary that after the drop function works, the entire dragndrop stops working, that is, when the user transfers 1 object, the dragndrop turns off and the second object will no longer be able to be transferred.
I tried to Implement it via async function and await new Promise. Here is the code itself:

async function dragndrop3Orange() {

    let flag = false;

    await new Promise(resolve => {

        const  square3 = document.querySelectorAll('.square3');
        const checker3 = document.querySelectorAll('.checker3__orange');


        const dragstart = function () {
            setTimeout(() => {this.classList.toggle('hide');}, 0);
        };

       const dragend = function () {
            setTimeout(() => {this.classList.toggle('hide');}, 0);
        };  

        checker3.forEach(element => {
            element.addEventListener('dragstart', dragstart);
            element.addEventListener('dragend', dragend);

        });


        const dragover = function(event) {
            event.preventDefault();
        };
      
        const drop = function() {
            console.log('drop');
            checker3.forEach(element => {
                if (element.classList.contains('hide') === true) {
                    this.prepend(element);
                }
                
            });
            this.classList.remove('hovered');
            resolve(flag  = true);   // я сделал флаг тру
        };
        square3.forEach(element => {
            element.addEventListener('dragover', dragover);
            element.addEventListener('drop', drop);
        });
    });

    console.log(flag);// флаг стал true

    if(flag === true){
        return;  //почему функция не останавливается и объекты дальше можно двигать?
    }
}

dragndrop3Orange();


https://codepen.io/sightLS/pen/mdpoYqb

Answer the question

In order to leave comments, you need to log in

1 answer(s)
B
boomer_tm, 2022-04-22
@boomer_tm

You need to move the flag check to the drop function

const drop = function() {
if(flag === true){
        return;  //почему функция не останавливается и объекты дальше можно двигать?
    }
            console.log('drop');
            checker3.forEach(element => {
                if (element.classList.contains('hide') === true) {
                    this.prepend(element);
                }
                
            });
            this.classList.remove('hovered');
            resolve(flag  = true);   // я сделал флаг тру
        };

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question