【问题标题】:Edit settimeout on autofill javascript在自动填充 javascript 上编辑 settimeout
【发布时间】:2015-11-23 17:57:46
【问题描述】:

我想放置一个命令,例如让我改变点击后的等待时间

var myVar;
    
function myFunction() {
  myVar = setTimeout(alertFunc, 3000);
}

function alertFunc() {
  alert("Hello!");
}
<p>Click the button to wait 3 seconds, then alert "Hello".</p>

<button onclick="myFunction()">Try it</button>

【问题讨论】:

  • 你有什么问题?

标签: javascript settimeout autofill


【解决方案1】:

这可以通过 jQuery 轻松实现。

$(".my-button").on("click", function(e){
    e.preventDefault();
    setTimeout(function(){
        alert("hello");
   }, 3000);
})

【讨论】:

  • 除非 OP 指定 jQuery,否则最好不要推荐它作为答案。
【解决方案2】:

Plunkr Example with enhanced code

JS

// Code goes here

var myVar;

function myFunction() {
  // this is to make sure we don't spin up infinite timeouts and have zombie threads
  if(myVar === undefined) {
    myVar = setTimeout(alertFunc, 3000);
  } else {
    alert("already running...");
  }
}

function alertFunc() {
  alert("hello!");
  // clears the thread
  clearTimeout(myVar);
  myVar = undefined;
}

您的代码

您的代码似乎工作得很好,alert 不在堆栈溢出沙箱中时也可以工作,我唯一添加的是使用 clearTimeout 清除超时,这样它就不会无限地运行。

var myVar;
    
function myFunction() {
  myVar = setTimeout(alertFunc, 3000);
}

function alertFunc() {
  console.log("Hello!");
  clearTimeout(myVar);
}
<p>Click the button to wait 3 seconds, then alert "Hello".</p>

<button onclick="myFunction()">Try it</button>

【讨论】:

    猜你喜欢
    • 2019-12-10
    • 2021-07-19
    • 1970-01-01
    • 2019-06-09
    • 2018-08-06
    • 1970-01-01
    • 2021-03-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多