单击“终止"可终止所有正在运行的JavaScript函数 [英] Kill all running JavaScript functions with Timeouts on click

查看:59
本文介绍了单击“终止"可终止所有正在运行的JavaScript函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有3个按钮和一个结果"部分的网页:

I have a webpage with 3 buttons and a "result" section:

<button id="b1" onclick="f1()">1st button</button>
<button id="b2" onclick="f2()">2nd button</button>
<button id="b3" onclick="f3()">3rd button</button>
<p id="result">"Here will be the result!"</p>

以下是JavaScript函数的代码段:

Here are the snippets for the JavaScript functions:

var to;

function f1() {
    // Kill other running instances of all functions
    to = setTimeout(() => {
        document.getElementById("result").innerHTML = "1st function";
    }, 10000 * Math.random());
}

f2 f3 基本相同,但是在少于10秒的暂停后打印不同的输出.

f2 and f3 are basically the same, but prints different outputs after the less-than-10-second pause.

但是,如果用户单击 b1 ,然后立即单击 b2 ,则 f1 f2 中在之后运行,并且输出将是 1st函数,而不是 2nd函数

However, if the user clicks b1 and then immediately click b2, there is a possibility that the innerHTML within f1 gets run after that in f2, and the output would be 1st function, instead of 2nd function.

我想要的是在每个功能的开头实现一条语句,该语句终止/忽略/绕过当前正在运行的所有功能,以便最终输出始终是与用户按下的最后一个按钮相关联的输出.如何最好地实施?

What I want is to implement, at the start of each function, a statement that kills/ignores/bypasses all functions that are currently running so that the final output would always be the one associated with the last button the user pressed. How can it be best implemented?

推荐答案

您可以设置所有函数都可以看到的全局变量,并使用它存储 setTimeout()的返回值.您已经在执行此操作.您现在要做的就是在每个函数的开头调用 clearTimeout(),以防止执行上一个调用.

You can set a global variable that all the functions can see and use it to store the return value from setTimeout(). You are already doing this. All you need to do now is call clearTimeout() at the head of each function to prevent the previous call from executing.

结果将是最后一个被按下的按钮将是唯一获胜的按钮.

The effect will be that the last button to be pressed will be the only one that wins.

var to;

function f1() {
  clearTimeout(to)
  // Kill other running instances of all functions
  to = setTimeout(() => {
    document.getElementById("result").innerHTML = "1st function";

  }, 3000 * Math.random());
}

function f2() {
  clearTimeout(to)
  // Kill other running instances of all functions
  to = setTimeout(() => {
    document.getElementById("result").innerHTML = "2nd function";

  }, 3000 * Math.random());
}

function f3() {
  clearTimeout(to)
  // Kill other running instances of all functions
  to = setTimeout(() => {
    document.getElementById("result").innerHTML = "3rd function";

  }, 3000 * Math.random());
}

<button id="b1" onclick="f1()">1st button</button>
<button id="b2" onclick="f2()">2nd button</button>
<button id="b3" onclick="f3()">3rd button</button>
<p id="result">"Here will be the result!"</p>

这篇关于单击“终止"可终止所有正在运行的JavaScript函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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