Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/429.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何使函数在刻度上的两个值之间反弹?_Javascript_Reactjs - Fatal编程技术网

Javascript 如何使函数在刻度上的两个值之间反弹?

Javascript 如何使函数在刻度上的两个值之间反弹?,javascript,reactjs,Javascript,Reactjs,我正在尝试创建一个函数,它首先将值设置为0,但经过一段时间后,它将变量设置为新值,然而,经过一段时间后,它再次将变量设置为0,并且它必须在这些值之间不确定地跳转 if (this.descriptionRef.current) { const { scrollHeight } = this.descriptionRef.current setTimeout(function run() { this.setState({ y: scrollH

我正在尝试创建一个函数,它首先将值设置为0,但经过一段时间后,它将变量设置为新值,然而,经过一段时间后,它再次将变量设置为0,并且它必须在这些值之间不确定地跳转

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等等)