简体   繁体   中英

setInterval doesn't work when used in a function

I am writing a JS program to record media and output the results every few seconds. I use setInterval to call MediaRecorder.requestData() every few seconds, but this is never called.

I have add console.log debugging outputs to the interval function but they are not output, because the interval is not being called.

function interval() {
    mediaRecorder.requestData();
}
function stream() {
    if (navigator.mediaDevices) {
        var constraints = {audio : true, video : true};
        navigator.mediaDevices.getUserMedia(constraints)
        .then(function(stream) {
            mediaRecorder = new MediaRecorder(stream);
            mediaRecorder.start();
            mediaRecorder.ondataavailable = sendData;
        });
        interval = window.setInterval(interval, 30000);
    }
}

mediaRecorder is a global variable and sendData is a function that will process the blob and log it to the console.

I expect the call to interval() to occur every 30 seconds. There are no error messages in the console, but it seems that interval() is never called and that sendData() is called only when the recording is stopped manually in the browser.

I fixed it by changing the name of the interval callback function to intervalCallback because of a conflict with the variable name. Thanks @Musa for advice.

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