防止alert()停止执行JavaScript [英] Prevent alert() from halting the execution of JavaScript

查看:37
本文介绍了防止alert()停止执行JavaScript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,我知道JavaScript是单线程的.可以说我有一个计数器,它每秒输出一次其值.

First of all , i know that JavaScript is single threaded. Lets say i have a counter that outputs its values every second.

var counter = 0;
setInterval(function(){
        console.log("Interval:  " + ++counter);

    }, 1000);

在某个时候,我想触发一些代码,以中止脚本的执行.例如,警报消息.

At some point, i want to trigger some code that halts the execution of the script. For example, an alert message.

setTimeout(function(){
    alert("Some alert message");
},10000);

此时,当警报消息弹出时,间隔代码将停止.有没有把戏,所以它不会停止执行?

At this point when the alert message popped, the interval code will halt. Is there a trick so it will not stop executing?

推荐答案

取决于您需要支持的浏览器(请检查 WebWorkers 以在并行线程中执行脚本.您只需要将代码拆分为单独的文件,即可在工作线程中运行的代码位于其自己的文件中.调整示例而不涉及工作人员的详细信息,您可以设置一个包含以下代码的文件 worker.js :

Depending on the browsers you need to support (check browser compatibility), you could use WebWorkers to execute scripts in parallel threads. You just need to split up your code into separate files, so that the code, which is to run in a worker thread, is in its own file. Adjusting your example without going into details of the worker you could set up a file worker.js containing the following code:

// file worker.js
var counter = 0;
setInterval(function(){
        console.log("Interval:  " + ++counter);

        // The worker will live until you kill it.
        if (counter > 100) self.close();  
}, 1000);

然后,您的主要JavaScript文件将设置新工作程序,使其在单独的工作程序线程中运行.

Your main JavaScript file will then set up the new worker to have it run in a separate worker thread.

// Set up the new worker in a separate thread.
var worker = new Worker("worker.js");

setTimeout(function(){
    // This will not stop the worker from logging to console.
    alert("Some alert message");
},10000);

因此,主线程中的 alert()不会停止执行工作线程,而是继续记录到控制台.

Thus, the alert() in the main thread will not stop the execution of the worker thread, which will continue logging to console.

有关此实时演示,请参见 Plunk .

See this Plunk for a live demo.

这篇关于防止alert()停止执行JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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