简体   繁体   English

使用javascript在后台运行任务

[英]Running a task in the background using javascript

I have a widget that displays a "waiting" image whenever a user submits a form, implemented with the following code: 我有一个小部件,每当用户提交表单时,该小部件都会显示一个“正在等待”的图像,并通过以下代码实现:

<div id="shading"></div>
<div id="spinner-wrapper">
    <div id="spinner-target"></div>
</div>


$("form").submit(function() {
    $("#spinner-wrapper").css({"visibility": "visible", "display": "block" });
    $("#shading").css({"z-index": "97"});
    var target = document.getElementById('spinner-target');
    var spinner = new Spinner(opts).spin(target);       
});         

This has the desired effect of graying out the screen, showing the spinner, and then when the form is done submitting, the user is directed to the target page. 这具有使屏幕变灰,显示微调器的期望效果,然后在完成表单提交后,将用户定向到目标页面。

However, sometimes the form is being submitted such that there is no redirect - specifically, if the user selects that they want to download a file, I return the file itself, and kill the process to block the redirect from occurring. 但是,有时提交表单时不会进行重定向-具体来说,如果用户选择要下载文件,我将返回文件本身,并终止阻止重定向发生的过程。 When this happens, the spinner remains in the foreground, blocking the user from interacting with the site - not the desired behavior. 发生这种情况时,微调框将保留在前台,阻止用户与站点进行交互-而不是所需的行为。

How could I somehow say that after X number of seconds (considering the target usage of the application, this would suffice), to stop/hide the spinner - that is, allow the form to be submitted, then show the spinner, then hide it (while this function does that in a different order - shows the spinner, then submits the form)? 我怎么能这样说,在X秒钟后(考虑到应用程序的目标使用情况,这就足够了),停止/隐藏微调框-也就是说,允许提交表单,然后显示微调框,然后隐藏它(虽然此功能以不同的顺序执行-显示微调框,然后提交表单)?

Use window.setTimeout(): 使用window.setTimeout():

$("form").submit(function() {
    $("#spinner-wrapper").css({"visibility": "visible", "display": "block" });
    $("#shading").css({"z-index": "97"});
    var target = document.getElementById('spinner-target');
    var spinner = new Spinner(opts).spin(target);       

    window.setTimeout(function() {
      //Hide the spinner here
    }, 5000); //Wait five seconds before running the callback function
});         

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

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