简体   繁体   English

javascript函数延迟不止一次

[英]javascript function delay more than once

I have coded here a function that would execute after 4 seconds but it would only wait 4 seconds once, because when i would trigger it again the second time the delay seems to not work anymore. 我在这里编写了一个将在4秒后执行的函数,但是它只会等待4秒一次,因为当我第二次再次触发它时,延迟似乎不再起作用。 Here is my sample code: 这是我的示例代码:

setTimeout(function sampleFunction() {
    alert("sample alert");
}, 4000);

my function is triggered by pressing a button. 按下按钮即可触发我的功能。 i want it to have a delay every time i press the button. 我希望每次按下按钮都会有延迟。 I want to use this delay function more than once, but the delay only works once. 我想多次使用此延迟功能,但延迟只能使用一次。 How do I make it work more than once? 我如何使其不止一次地工作? Thanks in advance. 提前致谢。

Here is the button that triggers it: 这是触发它的按钮:

<a data-role="button" onClick="sampleFunction( )">Trigger Button</a>

Use setInterval instead of setTimeout . 使用setInterval而不是setTimeout This will cause it to run every 4 seconds. 这将使其每4秒运行一次。 If you need to stop it, you can use clearInterval to stop it. 如果需要停止它,可以使用clearInterval停止它。 To do that, though, you need to save the return value of setInterval somewhere. 但是,为此,您需要将setInterval的返回值保存在某个地方。

Edit: To trigger it based on a button click, you need to make sure you have an onclick handler ( $('#whatever_id').on('click', ...) if you're using jQuery). 编辑:要基于按钮单击触发它,需要确保您具有onclick处理程序(如果使用jQuery $('#whatever_id').on('click', ...) )。 You can use this code: 您可以使用以下代码:

btn = document.getElementById('mybutton');

btn.onclick = function() {
    setTimeout(function sampleFunction() {
        alert("sample alert");
    }, 200);
};

Working jsFiddle 工作jsFiddle

UPDATE: 更新:

With the new inforamtion you provided, it sounds like you just need to set an event handler to the button: 使用您提供的新信息,听起来您只需要为按钮设置事件处理程序即可:

document.getElementById('buttonId').addEventListener('click', function () {
    setTimeout(function() {
        alert('test');
    }, 4000);
}, false);

ORIGINAL: 原版的:

Either use setInterval or use setTimeout (preferred). 使用setInterval或使用setTimeout(首选)。

var timer = setTimeout(function timerFn() {
    alert('test');
    timer = setTimeout(timerFn, 1000);
}, 1000);

Doing it with setTimeout ensures that the function is only called once in the timeout length. 使用setTimeout进行操作可确保该函数在超时长度内仅被调用一次。

If you use setInterval it is possible for callbacks to build up and all be executed one after the other. 如果使用setInterval,则可能会建立回调,并且一个接一个地执行所有回调。 This is not the case with setTimeout. setTimeout并非如此。

You're calling the function, so it's executing. 您正在调用该函数,因此它正在执行。 If you want the setTimeout, you'll need to call a function that contains it. 如果需要setTimeout,则需要调用包含它的函数。 Try this: 尝试这个:

function sampleFunction() {
    setTimeout(function {
        alert("sample alert");
    }, 4000);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM