Javascript 如何使函数在刻度上的两个值之间反弹?
我正在尝试创建一个函数,它首先将值设置为0,但经过一段时间后,它将变量设置为新值,然而,经过一段时间后,它再次将变量设置为0,并且它必须在这些值之间不确定地跳转Javascript 如何使函数在刻度上的两个值之间反弹?,javascript,reactjs,Javascript,Reactjs,我正在尝试创建一个函数,它首先将值设置为0,但经过一段时间后,它将变量设置为新值,然而,经过一段时间后,它再次将变量设置为0,并且它必须在这些值之间不确定地跳转 if (this.descriptionRef.current) { const { scrollHeight } = this.descriptionRef.current setTimeout(function run() { this.setState({ y: scrollH
if (this.descriptionRef.current) {
const { scrollHeight } = this.descriptionRef.current
setTimeout(function run() {
this.setState({ y: scrollHeight })
console.log(scrollHeight)
setTimeout(run, 7000)
}, 7000)
}
因此,我有一个嵌套的setTimeout函数,它必须执行滴答的部分,但我需要以某种方式更改setState值。您能使用setInterval吗
let x = 0
setInterval(() => x = x === 0 ? "something else" : 0, 7000)
import React,{useState,useffect}来自“React”;
从“react dom”导入react dom;
函数App(){
const[number,setNumber]=useState(0);
useffect(()=>{
如果(数字==10){
设置超时(()=>{
设置编号(90)
}, 1000);
}否则{
设置超时(()=>{
设置编号(10)
}, 1000);
}
},[编号];
返回(
{number}
);
}
const rootElement=document.getElementById(“根”);
render(,rootElement);
您可以使用发电机功能
function* switchValues (value) {
while(true){
yield 0;
yield value;
}
}
const valueSwitcher = switchValues({ y: 10 })
console.log(valueSwitcher.next().value) //0
console.log(valueSwitcher.next().value) //the value you passed in, in this case an object
它将在您上次离开它的位置(屈服后)拾取函数的执行
您可以尝试在代码中这样使用:
if (this.descriptionRef.current) {
const { scrollHeight } = this.descriptionRef.current
setTimeout(function run() {
this.setState(valueSwitcher.next().value)
console.log(scrollHeight)
setTimeout(run, 7000)
}, 7000)
}
您可以在其内部执行
setInterval
和条件setState
,根据以前的值设置新值(0到新值,新值到0等等)