首页 > 解决方案 > 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() {...}(以及其他功能,似乎都不起作用)。

这一定是我想念的简单东西吧?

jsfiddle在这里

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>

标签: javascriptsetinterval

解决方案


该代码有点尝试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

推荐阅读