【问题标题】:Javascript Delay to change Boolean [duplicate]Javascript延迟更改布尔值[重复]
【发布时间】:2021-08-03 01:16:48
【问题描述】:

我试图让它在一段时间后,一个以 false 开始的布尔值变为 true,我到目前为止的代码在这里,我不知道如何设置一个计时器,我可以得到有什么帮助吗?

var alert1 == false;

if (alert1) {
alert ("Hello!");
} else {
}

【问题讨论】:

标签: javascript boolean


【解决方案1】:

你使用setTimeout

var alert1 = false;
// check alert1 value every second
setInterval(()=>{console.log(alert1)}, 1000);
// change it after 5s
setTimeout(() => {alert1 = true;}, 5000);

【讨论】:

    【解决方案2】:

    使用setTimeout 为执行代码添加延迟。

    setTimeout(function () {
        alert1 = true;
    }, YOUR_DELAY_TIME_IN_MILLISECONDS); // Replace with how much time you want to wait
    

    您的代码将无法工作,因为您在脚本运行开始时检查了alert1 是否为真,但片刻之后alert1 将变为true。您不会检查alert1 是否为真您实际上将其更改为真。如果您希望它在几秒钟内发出警报,则不需要布尔值。

    setTimeout(function () {
        alert("Hello!")
    }, 2000); // Replace with how much time you want to wait in milliseconds (this is 2000 milliseconds, which is 2 seconds)

    【讨论】:

      【解决方案3】:

      使用setTimeout() 方法,您可以在milliseconds 中提供时间,然后您的代码将被执行。

      let alert = false;
      
      console.log("Begin..... ", alert);
      setTimeout(() => {
        alert = true;
        console.log("after 2 secs: ", alert);
      }, 2000);

      查看here了解更多详情。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-12-30
        • 2013-09-13
        • 2020-02-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-01-29
        相关资源
        最近更新 更多