我有一个涉及眨眼检测的JavaScript函数,它会影响一个视频。基本上,当你眨眼时,从YouTube嵌入的视频会停止播放,并且会弹出一个确认对话框,允许你继续观看视频或重新加载页面。一旦我点击“确定”,视频应该继续播放,但我希望函数停止(或者摄像头停止工作),这样即使你眨眼也能继续观看到视频结束。
我尝试修改这个函数,但没有找到我的错误所在。
这是函数的主要代码:
function blink() { _blinked = true; _total += 1; const now = new Date(); const timeDiff = (now - _start) / 1000; //in s // get seconds const seconds = Math.round(timeDiff); if(confirm(`You lasted ${seconds} seconds without blinking! Click OK to keep playing or CANCEL to watch full video!`)){} else window.location.replace("fullvideo.html"); _start = new Date(); if (_timeOut > -1) { clearTimeout(_timeOut); } _timeOut = setTimeout(resetBlink, 500);}function resetBlink() { _blinked = false;}let _initialized = false;
一旦我点击“确定”,视频应该继续播放,但我希望函数停止(或者摄像头停止工作),这样即使你眨眼也能继续观看到视频结束。非常感谢你。
回答:
最简单的方法是使用一个全局布尔值,由每个函数切换。我们在这里称之为status:
var status = false;function blink() { if (!status){ status = true; // 关闭函数 _blinked = true; _total += 1; const now = new Date(); const timeDiff = (now - _start) / 1000; //in s // get seconds const seconds = Math.round(timeDiff); if(confirm(`You lasted ${seconds} seconds without blinking! Click OK to keep playing or CANCEL to watch full video!`)){ status = false; // 重新开启函数运行 } else window.location.replace("fullvideo.html"); _start = new Date(); if (_timeOut > -1) { clearTimeout(_timeOut); } _timeOut = setTimeout(resetBlink, 500); } }
现在你的函数只会运行一次,然后如果你在消息上点击“确定”,它应该能够再次运行一次。