setTimeOut 不起作用 - 它循环很糟糕

setTimeOut not work - it loops badly

我想做一个重复函数来检索 selected select 的值并将其发送到变量

 function choosepr(){
var a = document.getElementById("projects");
var b = a.options[a.selectedIndex].value;   // get value from select

projectimg(b);
projectbutton(b);
projectdesc(b);

setTimeout(choosepr(),200);   //repeat function after 200ms
}

变量"b"获取正确的值并且函数正确接收并执行,问题出在setTimeout,因为激活此函数后它不会以200毫秒的频率循环,它只会暂停电脑一段时间后停止执行。

如何修复它并制作良好的循环?

已满 HTML:https://pastebin.com/WVXQrFSf 完整的 JS:https://pastebin.com/AAW6wZCt

与其使用 setTimeout 方法,不如使用 setInterval 方法。这种方法将比 setTimeout 方法更准确,因为 setTimeout 等待 200 毫秒,运行函数然后设置另一个超时。所以等待时间实际上超过 200 毫秒(如果您的函数需要很长时间才能执行,则等待时间会更长)。

虽然有人可能认为 setInterval 会恰好每 200 毫秒执行一次,但重要的是要注意 setInterval 也会延迟,因为 JavaScript 不是多线程语言,这意味着 - 如果脚本的其他部分 运行 - 间隔将不得不等待它完成。

尝试使用setInterval调用此方法。

function choosepr(){
var a = document.getElementById("projects");
var b = a.options[a.selectedIndex].value;   // get value from select

projectimg(b);
projectbutton(b);
projectdesc(b);
}

setInterval(choosepr, 200);

您需要从 choosepr 中删除括号,因为您不应调用该函数,而应将其传递给 setTimeout

setTimeout(choosepr,200);   

更好的解决方案是使用 setInterval

function choosepr()
{
        var a = document.getElementById("projects");
        var b = a.options[a.selectedIndex].value;  
        projectimg(b);
        projectbutton(b);
        projectdesc(b);
}

setInterval(choosepr , 200);