出现警告框时 Javascript 计时器暂停 [英] Javascript timer paused when alert box appears

查看:26
本文介绍了出现警告框时 Javascript 计时器暂停的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的程序计算用户猜出每个州的正确名称所需的时间.

当用户点击状态所在的星星时,会出现一个输入框,要求用户输入状态的名称.

当我按下开始按钮时,计时器开始计时,但当我选择一颗星星输入答案时,计时器停止.

即使在调用警报后,如何使计时器继续运行?

我的脚本文件

var startButton = document.getElementById("startButton");var messages = document.getElementById("messages");var timeId,分数;无功计数 = 0;状态 = 50;startButton.addEventListener("click", startTimer);函数开始定时器(){startButton.removeEventListener("click", startTimer);timeId = window.setInterval(displayNumber, 1000);}函数显示编号(){计数++;messages.innerHTML = 计数;如果(计数== 10){alert("时间到");分数 = (正确选择 - 不正确选择) * 2;alert("你的分数是" + correctChoice);window.clearInterval(timeId);}}

附加脚本文件

var CorrectChoice = 0;变量不正确选择 = 0;document.getElementById("California").addEventListener("click", choice1);功能选择1(e){if (e.type == "click") {input = window.prompt("什么是状态");}如果(输入!=加利福尼亚"){alert("错误答案");} 别的 {alert("正确答案")正确选择++;//注释父/子节点var image1 = document.getElementById('加利福尼亚');image1.parentNode.removeChild(image1);如果(正确选择 == 2){alert("你都猜对了");分数 = (正确选择 - 不正确选择) * 2;alert("你的分数是" + correctChoice);}}}

HTML

<头><meta charset="utf-8"><标题>内存</title><style type="text/css">身体 {背景图片:网址(usa.jpg");背景尺寸:900px 600px;背景重复:不重复;}</风格><身体><div style="position: absolute; right: 10px; top: 10pt"><input type="button" value="开始!"id="startButton" style="width:80px"/><input type="button" value="Reset" id="resetButton" style="width:80px" onClick="window.location.reload()"/><h2 id="消息">

<img src="state.png" id="California" value="California" width="30px" height="30px" style="position: absolute; left: 130px; top: 200pt"/><script src="simonSays.js"></script><script src="script.js"></script></html>

解决方案

Kieran 说的对,提示会阻塞执行但工作程序或其他线程对于您的简单应用程序来说太过分了.

您需要的是计算时差.增加变量并不可靠,因为它更多是检查次数而不是时间计数.

var startTime = new Date(),时间限制 = 10;//片刻之间函数 getElapsed() {返回 (new Date() - startTime)/1000;}函数 isTimesUp() {返回 getElapsed() >= timeLimit;}函数提示用户(){var input = window.prompt("什么是状态");//在检查答案之前,确保还有时间.if (isTimesUp()) 返回 timesUp();//否则检查答案是否正确}

用户输入答案的时间现在无关紧要,因为检查是为了确保在批准答案之前还有时间.

概念证明

var startButton = document.getElementById("startButton"),testButton = document.getElementById("testButton"),resetButton = document.getElementById("resetButton"),timerEl = document.getElementById('timer'),timeLimit = 10,//以秒为单位开始时间,时间标识;startButton.addEventListener("click", startTimer);resetButton.addEventListener("click", reset);testButton.addEventListener("click", promptUser);函数开始定时器(){如果(timeId)返回;timerEl.innerHTML = "0";timeId = window.setInterval(displayNumber, 500);开始时间 = 新日期();}功能重置(){window.clearInterval(timeId);timerEl.innerHTML = "-";时间 ID = 空;}函数 getElapsed() {返回 (new Date() - startTime)/1000;}函数 isTimesUp() {返回 getElapsed() >= timeLimit;}函数 timesUp() {重启();alert("时间到");//显示分数}函数显示编号(){var elapsed = getElapsed();timerEl.innerHTML = Math.floor(elapsed);if (elapsed >= timeLimit) {时间到();}}函数提示用户(){var input = window.prompt("什么是状态");if (isTimesUp()) 返回 timesUp();//否则检查答案是否正确}

缺点是计时器看起来像是在后台冻结,但一旦提示关闭,计时器将返回到它从不冻结的位置,跳过中间的任何数字.

此外,您无需刷新页面即可重置,您可以像单页应用程序一样处理脚本中的所有内容.

更好的解决方案

使用 JavaScript 制作交互式应用程序的更好方法是避免使用默认浏览器对话框(警报、提示、等).

来自关于alert的MDN文档:

<块引用>

对话框是模态窗口 - 它们阻止用户访问程序界面的其余部分,直到对话框关闭.出于这个原因,您不应该过度使用任何创建对话框(或模态窗口).

改为使用可以风格化的定制模态,例如 Bootstrap modalsjQuery 的对话框.这些类型的 JavaScript 模式不会停止代码执行,因此计时器元素仍会在后台更新.

My program counts how long it takes a user to guess the correct name of each state.

When the user clicks the star where the state is, an input box appears, asking the user to type the name of the state.

When I hit the start button the timer begins, but when I select a star to input the answer, the timer stops.

How can I make the timer continue even after an alert is called?

My script file

var startButton = document.getElementById("startButton");
var messages = document.getElementById("messages");
var timeId, score;
var count = 0;
states = 50;

startButton.addEventListener("click", startTimer);

function startTimer() {
    startButton.removeEventListener("click", startTimer);
    timeId = window.setInterval(displayNumber, 1000);

}

function displayNumber() {
    count++;
    messages.innerHTML = count;
    if (count == 10) {
        alert("time's up");
        score = (correctChoice - incorrectChoice) * 2;
        alert("your score is " + correctChoice);
        window.clearInterval(timeId);
    }
}

additional script file

var correctChoice = 0;
var incorrectChoice = 0;

document.getElementById("California").addEventListener("click", choice1);

function choice1(e) {
    if (e.type == "click") {
        input = window.prompt("What is the state");
    }
    if (input != "California") {
        alert("wrong answer");
    } else {
        alert("Correct Answer")
        correctChoice++;
        //comment on parent/child node
        var image1 = document.getElementById('California');
        image1.parentNode.removeChild(image1);
        if (correctChoice == 2) {
            alert("you have guessed them all correctly");
            score = (correctChoice - incorrectChoice) * 2;
            alert("your score is " + correctChoice);
        }
    }
}

HTML

<!DOCTYPE HTML>
<html>
<head>
    <meta charset="utf-8">
    <title> MEMORY </title>

    <style type="text/css">
        body {
            background-image: url("usa.jpg");
            background-size: 900px 600px;
            background-repeat: no-repeat;
        }
    </style>
    <body>
        <div style="position: absolute; right: 10px; top: 10pt">
            <input type="button" value="Start!" id="startButton" style="width:80px" />
            <input type="button" value="Reset" id="resetButton" style="width:80px" onClick="window.location.reload()" />

            <h2 id="messages"> </h2>
        </div>
        <img src="state.png" id="California" value="California" width="30px" height="30px" style="position: absolute; left: 130px; top: 200pt" />
    </body>

    <script src="simonSays.js"></script>
    <script src="script.js"></script>
</html>

解决方案

Kieran is right in saying that the prompt blocks the execution but a worker or another thread is overkill for your simple app.

What you need is to calculate time difference. Incrementing a variable isn't reliable as it's more of a number of checks than it is a time count.

var startTime = new Date(),
    timeLimit = 10; // in seconds

function getElapsed() {
    return (new Date() - startTime) / 1000;
}

function isTimesUp() {
    return getElapsed() >= timeLimit;
}

function promptUser() {
    var input = window.prompt("What is the state");
    // before checking the answer, ensure that there's time left.
    if (isTimesUp()) return timesUp();
    // else check if the answer is correct
}

The time for the user to enter an answer is now irrelevant as a check is there to make sure that there's time left before approving the answer.

Proof of concept

var startButton = document.getElementById("startButton"),
  testButton = document.getElementById("testButton"),
  resetButton = document.getElementById("resetButton"),
  timerEl = document.getElementById('timer'),
  timeLimit = 10, // in seconds
  startTime,
  timeId;

startButton.addEventListener("click", startTimer);
resetButton.addEventListener("click", reset);
testButton.addEventListener("click", promptUser);

function startTimer() {
  if (timeId) return;
  timerEl.innerHTML = "0";
  timeId = window.setInterval(displayNumber, 500);
  startTime = new Date();
}

function reset() {
  window.clearInterval(timeId);
  timerEl.innerHTML = "-";
  timeId = null;
}

function getElapsed() {
  return (new Date() - startTime) / 1000;
}

function isTimesUp() {
  return getElapsed() >= timeLimit;
}

function timesUp() {
  reset();
  alert("time's up");
  // display score
}

function displayNumber() {
  var elapsed = getElapsed();
  timerEl.innerHTML = Math.floor(elapsed);
  if (elapsed >= timeLimit) {
    timesUp();
  }
}

function promptUser() {
  var input = window.prompt("What is the state");
  if (isTimesUp()) return timesUp();
  // else check if the answer is correct

}

<button type="button" id="startButton">Start</button>
<button type="button" id="resetButton">Reset</button>
<button type="button" id="testButton">Test Answer</button>
<div>Timer: <span id="timer">-</span>
</div>

The downside is that the timer will look like it froze in the background but once the prompt closed, the timer will take back to where it would be if it never froze, skipping any number in between.

Also, you don't need to refresh the page to reset, you can handle everything in the scripts like a single-page app would.

Better solution

A better way to make interactive application with JavaScript is to avoid default browser dialog boxes (alert, prompt, et.).

From the MDN documentation on alert:

Dialog boxes are modal windows - they prevent the user from accessing the rest of the program's interface until the dialog box is closed. For this reason, you should not overuse any function that creates a dialog box (or modal window).

Instead use custom made modals, which can be stylized, like Bootstrap modals or jQuery's Dialog. These types of JavaScript modal don't stop code execution, so the timer element would still be updated in the background.

这篇关于出现警告框时 Javascript 计时器暂停的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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