简体   繁体   中英

JavaScript calling function 4 times but I need to execute function only one time

I have listener when any change in volume execute callback function 4 times callback call other function I need that function execute only one what is the best way

when lisiner detect any change callback call recognitionCameraBySoundVolum() 4 time

volumeListener = SystemSetting.addVolumeListener((data) => { 
    recognitionCameraBySoundVolum();
});

need to excute this function only once instead of 4

   const recognisionCameraBySoundVolum = () => {
        console.log("hi from recognitionCameraBySoundVolum "); 
    }

Did you use the useEffect hook?

It should look something like this.

useEffect(() => {
    volumeListener = SystemSetting.addVolumeListener((data) => { 
        recognitionCameraBySoundVolum();
    });

    // return remove listener method in the cleanup section 
}, []);

this worked with me

useEffect(() => {
const volumeListener = SystemSetting.addVolumeListener( (data) => { 
    const volume = data.value;  

}); 
return () => 
SystemSetting.removeVolumeListener(volumeListener)  
}, [])

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