我创建了我的第一个二维码扫描仪
我的第一个版本是这样的
function decodeQRCode(photo) {
const scanner = new BarcodeDetector({
formats: ['qr_code']
})
scanner.detect(photo)
.then((barcodes) => {
bar_length = barcodes.length
if (bar_length != 0) {
barcodes.forEach(
(barcode) =>
input.setAttribute("value", barcode.rawValue),
);
input.addEventListener('input', form.submit())
setTimeout(takepicture, 3000);
console.log("success")
} else {
setTimeout(takepicture, 1500);
}
})
.catch((err) => {
console.error(err);
});
我的第二个版本看起来像这样
function decodeQRCode(photo) {
const scanner = new BarcodeDetector({
formats: ['qr_code']
})
setTimeout(() => {
scanner.detect(photo)
.then((barcodes) => {
bar_length = barcodes.length
if (bar_length != 0) {
barcodes.forEach(
(barcode) =>
input.setAttribute("value", barcode.rawValue)
);
input.addEventListener('input', form.submit())
} else {
takepicture()
}
})
.catch((err) => {
console.error(err);
});
}, 3000)
在我的第一个版本中,它设置为每 3 秒扫描一次二维码,因为我将其设置为延迟 3 秒调用
function takepicture()
,但 console.log("success")
不断打印出“成功”,直到我将相机指向远离 QRCode 的位置
在我的第二个版本中,我仍然使用 setTimeout 但带有箭头功能,它正在按照我想要的方式进行,即每 3 秒扫描一次
我只是真的不知道为什么它在我的第一个版本上不断打印,两者都设置为以 3 秒延迟调用
function takepicture()
,但只是采用不同的方法
很简单:
setTimeout(takepicture, 3000);
的作用就像一个异步函数。这意味着,代码执行该行,然后继续执行其余代码,而无需等待函数内部发生的情况(等待 3 秒,然后调用 takepicture
)。
在第二个版本中,您已将所有代码包装在
setTimeout
函数中,这会强制代码在执行该代码之前等待 3 秒。
换句话说:
setTimeout(takepicture, 3000);
console.log("success");
将立即打印“成功”,因为代码不会等待
setTimeout
函数完成。
但是:
setTimeout(() => {console.log("success");}, 3000);
等待3秒后打印“成功”。
希望有帮助。