Home > Back-end >  JavaScript calling function 4 times but I need to execute function only one time
JavaScript calling function 4 times but I need to execute function only one time

Time:07-16

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 "); 
    }

CodePudding user response:

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 
}, []);

CodePudding user response:

this worked with me

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

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