javascript 延迟点击事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17690193/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 09:12:56  来源:igfitidea点击:

Delaying click event

javascriptjquery

提问by nitarshan

I'm wondering whether there's a simple way to delay the click event from being processed for a specified period of time. For example we could have

我想知道是否有一种简单的方法可以将单击事件延迟处理一段指定的时间。例如我们可以有

$('#someElement').on('click', 'a', function(event) {
    var duration = 1000;
    someAsynchronousFunction(); // Start as soon as click occurs
    ... // Code to delay page transition from taking place for duration specified
});

So in this case the asynchronous function would be guaranteed some amount of time to run. If it hasn't completed it's work in this time I wouldn't care and would just like to continue with the page transition. I know that it's possible to accomplish something close with

所以在这种情况下,异步函数将被保证一定的时间来运行。如果它还没有完成它在这个时候的工作我不会在意,只想继续页面转换。我知道有可能完成一些与

event.preventDefault();
...
setTimeout(function(){
    window.location = $(this).attr('href');
}, duration);

But this only works when the link being clicked goes to a full page. I want to be able to deal with links that are used for ajax calls (which don't change the url) as well.

但这仅在被点击的链接进入整页时才有效。我也希望能够处理用于 ajax 调用(不更改 url)的链接。

I noticed that the mixpanel library has a function track_links which seems to accomplish the delay on the page transition, though that function doesn't seem to work well with the support for ajax links that I mentioned.

我注意到 mixpanel 库有一个函数 track_links,它似乎完成了页面转换的延迟,尽管该函数似乎不能很好地支持我提到的 ajax 链接。

Any help would be great! Thanks.

任何帮助都会很棒!谢谢。

Edit: So I suppose my question wasn't exactly clear, so I'll try to provide some more details below.

编辑:所以我想我的问题不是很清楚,所以我会尝试在下面提供更多细节。

I don't care if the async function finishes running! I only want to give it the guarantee that it has some set amount of time to execute, after which I don't care if it finishes, and would prefer to go ahead with the page transition.

我不在乎异步函数是否完成运行!我只想保证它有一定的执行时间,之后我不在乎它是否完成,并且更愿意继续进行页面转换。

i.e. I want to delay not the start of the async function, but the start of the page transition. The async function would start running as soon as the click occured.

即我想延迟不是异步函数的开始,而是页面转换的开始。一旦点击发生,异步函数就会开始运行。

Hopefully this is a bit more clear!

希望这更清楚一点!

回答by nitarshan

So in the end I figured out a way to solve the problem I posed, and I'm providing it here in case anyone else has the same problem and is looking for a solution.

所以最后我想出了一种方法来解决我提出的问题,我在这里提供它,以防其他人遇到同样的问题并正在寻找解决方案。

var secondClick = false;
var duration = 1000;

$('#someElement').on('click', 'a', function(event) {
    var that = $(this);

    if(!secondClick) {
        event.stopPropagation();
        setTimeout(function(){
            secondClick = true;
            that.click();
        }, duration);

        someAsynchronousFunction();
    } else {
        secondClick = false;
    }
}

Basically when the user clicks the link, it internally prevents that click from actually having any effect, and gives the asynchronous function a set amount of time to do it's work before doing a second click on the link which behaves normally.

基本上,当用户单击链接时,它会在内部阻止该单击实际产生任何影响,并在第二次单击行为正常的链接之前为异步函数提供一定的时间来完成它的工作。

回答by Isaac Suttell

setTimeoutallows you to delay running code by however many ms you want

setTimeout允许您将运行代码延迟多少毫秒

setTimeout(function(){
    console.log('Stuff be done'); //This will be delayed for one second
}, 1000);

In reality, if you're dealing with ajax you want to respond when the ajax call is complete. It may take more or less than 1000ms. $.ajaxallows you do this with the .done()method. This is an example from the docs:

实际上,如果您正在处理 ajax,您希望在 ajax 调用完成时做出响应。它可能需要多于或少于 1000 毫秒。$.ajax允许您使用该.done()方法执行此操作。这是文档中的一个示例:

$.ajax({
    url: "test.html",
    context: document.body
}).done(function() {
    $(this).addClass("done");
});

回答by Yevgen

I've added "flag" to @Sushanth's code:

我在@Sushanth 的代码中添加了“标志”:

Javascript

Javascript

$('#someElement').on('click', 'a', function(event) {
    var duration = 1000;
    var someAsynchronousFunction_status = false; // flag

    setTimeout(function() {
       if (!someAsynchronousFunction_status) {
            // this code will run after the duration elaspes but
            // ONLY if someAsynchronousFunction() return false or nothing
       }
    }, duration);

    someAsynchronousFunction_status = someAsynchronousFunction(); // redefine flag
});

If someAsynchronousFunction() returns anything but falseyou can try to make it this way.

如果 someAsynchronousFunction() 返回任何内容,但false您可以尝试这样做。

回答by user1937279

jQuery's ajax functionality provides exactly what you are looking for. You can define a callback function to run after your ajax request.

jQuery 的 ajax 功能正好提供您正在寻找的内容。您可以定义一个回调函数以在您的 ajax 请求之后运行。

Something like this:

像这样的东西:

$('#someElement').click(function(event){
    event.preventDefault();
    var loc = $(this).attr('href');
    $.ajax({
        url: "test.html",
        complete: function(){
            // Handle the complete event
            loc = $(this).attr('href');
            window.location.href = loc;
        }
    });
});

You may want to use ajaxStopinstead of complete, it seems like your motivation for delaying navigation is because you have a bunch of asynchronous stuff going on and you want to make sure all your ajax stuff is complete before you navigate to that page.

您可能想使用ajaxStop而不是complete,似乎您延迟导航的动机是因为您有一堆异步内容正在进行,并且您希望在导航到该页面之前确保所有 ajax 内容都已完成。

Regardless I would recommend looking at http://api.jquery.com/Ajax_Events/(a very useful page of documentation).

无论如何,我建议您查看http://api.jquery.com/Ajax_Events/(一个非常有用的文档页面)。

回答by Esteban Araya

window.setTimeoutwill execute any given function after a specified delay.

window.setTimeout将在指定的延迟后执行任何给定的函数。

You'd call it like this:

你会这样称呼它:

$('yourElement').click(function (event) {
    setTimeout(function () { console.log('hi'); }, 1000);
});

But I have to wonder why you need to do this. What's the problem you're trying to solve? Usually delaying stuff doesn't really solve anything.

但我想知道为什么你需要这样做。你要解决的问题是什么?通常拖延事情并不能真正解决任何问题。