请等待,然后才能再次调用javascript函数 [英] Wait before a javascript function can be called again

查看:49
本文介绍了请等待,然后才能再次调用javascript函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我研究了许多不同的解决方案,但没有一个可行.我知道它与setTimeout有关,但是我不知道如何正确实现它.

I've looked at many different solutions to this, none of which worked. I know it has something to do with setTimeout, but I don't know how to implement it properly.

function myfunction()
{
//the function
//wait for 1 second before it can be ran again
}

为了阐明这一点:我不想定期调用该函数,而是希望能够强制延迟一段时间才能再次调用该函数.

To clarify: I don't want to call the function at a regular interval, I want to be able to enforce a delay before the function can be called again.

推荐答案

我认为最简单的解决方案是保存一个 boolean 变量并将其重置为 true 给定 delay .

I think the easiest solution would be to hold a boolean variable and reset it to true after a given delay.

HTML

<button id="clickme">click me!</button>

JavaScript

var canGo = true,
    delay = 1000; // one second
var myFunction = function () {
    if (canGo) {
        canGo = false;
        // do whatever you want
        alert("Hi!");
        setTimeout(function () {
            canGo = true;
        }, delay)
    } else {
        alert("Can't go!");
    }
}


$("#clickme").click(function(){
    myFunction();
})

这样,您将拥有一个布尔值 canGo ,并将其设置为 true .如果运行该函数,则会将 canGo 设置为false,并在 delay 的时间段(以毫秒为单位)中设置 setTimeout().如果您尝试再次运行该函数,它将不会运行,而是运行 alert("Ca n't go!").这只是出于说明的目的;您不需要那部分. delay 之后, canGo 将设置为 true ,您将能够再次运行该功能.

With this, you hold a boolean, canGo, and set it to true. If the function is run, it sets canGo to false and sets a setTimeout() for a time period of delay, in milliseconds. If you try to run the function again, it won't run and will, instead, alert("Can't go!"). This was just for demonstrative purposes; you don't need that part. After delay, canGo will be set to true, and you will be able to once more run the function.

这篇关于请等待,然后才能再次调用javascript函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆