javascript - setInterval 函数未使用 JavaScript ES6 运行
问题描述
这让我如厕
const video = document.querySelector('.video'); // grab the element
const randomInt = () => Math.random().toFixed(2); // get random int from 0 - 1 and round to two decimal points
const runTimer = () => setInterval(randomInt, 100); // function to call randomInt every 100ms
video.style.opacity = runTimer(); // set the opacity at random every 100ms
我不知道这是否是 ES6 和使用隐式或显式返回的问题。FWIW我也尝试过使用繁体的Javascript,比如
runTimer() {...}
或者function runTimer() {...}
(以及其他功能,似乎都不起作用)。
这一定是我想念的简单东西吧?
const video = document.querySelector('.video'); // grab the element
const randomInt = () => Math.random().toFixed(2); // get random int from 0 - 1 and round to two decimal points
const runTimer = () => setInterval(randomInt, 100); // function to call randomInt every 100ms
video.style.opacity = runTimer(); // set the opacity at random every 100ms
video {
width: 100%;
}
<video class="video" poster="https://64.media.tumblr.com/tumblr_qsflcrfAoC1z0l4vz_smart1.jpg" preload="none" muted="" data-crt-video="" crossorigin="anonymous" tabindex="-1" loop controls>
<source src="https://va.media.tumblr.com/tumblr_qsflcrfAoC1z0l4vz_480.mp4" type="video/mp4">
</video>
解决方案
该代码有点尝试runTimer
在计时器间隔内调用它之前伸出并重用代码。函数无法做到这一点。
相反,将您要为每个间隔回调运行的所有逻辑(包括video.style.opacity =
部分)移动到您传递给的函数中setInterval
。见***
评论:
const video = document.querySelector('.video'); // grab the element
const randomInt = () => Math.random().toFixed(2); // get random int from 0 - 1 and round to two decimal points
const updateOpacity = () => video.style.opacity = randomInt(); // ***
const runTimer = () => setInterval(updateOpacity, 100); // function to call randomInt every 100ms
// *** −−−−−−−−−−−−−−−−−−−−−−−−−−−−^
runTimer(); // set the opacity at random every 100ms
推荐阅读
- c# - 像电开关这样的设计模式?
- reactjs - React-bootstrap Carousels 垂直渲染
- java - 将 kafka 日志消息重定向到单独的日志(catalina.out 除外)
- python - 如何通过 Python 在命令行应用程序中运行代码
- c# - 数学函数 - 绘图问题
- sql-server - Express 上的链接服务器和升级到 SQL Server 2014 Standard
- css - 有没有办法将唯一的 scss 文件导出到模块化 css 文件?
- google-cloud-platform - 从 Dataprep 导出结果配置文件
- python - 命令“python setup.py egg_info”失败,错误代码为 1 | 无法通过 python 和 pycharm 安装
- snakemake - Can snakemake create job error and output files automatically on a SLURM cluster?