如何制作一个计数 3 秒的函数 [英] How to make a function which counts for 3 seconds

查看:14
本文介绍了如何制作一个计数 3 秒的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写一个程序来计算电脑在 3 秒内可以完成多少计算步骤,它应该基本上像这样工作:

I want to make a programm which counts how many computational steps the pc can make in 3 seconds it should work basicly like this:

var i = 0;
function count(){
  while(the3seconds are not over)
  {
    i++;
    div.innerHTML = i;
  }
}

问题是一个无关紧要我如何尝试它不会在 3 秒和 2 秒后停止,因为它在循环中变量 i 在过程中没有被显示.

Problem is ONE doesnt matter how I trie it does not stop after 3 seconds and TWO because its in a loop the variable i is not displyed while the process.

如何解决这两件事?

var rechenschritte = 0;
var div = document.getElementById("rechenschritte");
function count(duration) {
    var end = new Date().getTime() + duration;
    
    while(new Date().getTime() < end) {
      rechenschritte++;
    }
    div.innerHTML = rechenschritte;
    rechenschritte = 0;
}

<!doctype html>
<html lang="de">
<head>
      <meta charset="UTF-8">
</head>
<body>

<input type="button" onclick="count(500)" value="Start"/>
<div id="rechenschritte"></div>

</body>
</html>

如何看它计数?

推荐答案

如果你想要一个阻塞功能比:

If you want to have a blocking function than:

var end = new Date().getTime() + 3000;
while(new Date().getTime() < end) {}

FIDDLE #1

但这会阻塞整个用户界面,如果你想要一个动画»循环«,比:

But this will block the whole UI and if you want an animation »loop«, than:

  (function loop (end) {

      //do stuff
      if (new Date().getTime() < end) {
          window.requestAnimationFrame(function(){
              loop(end);
          });
      }

  })(new Date().getTime() + 3000);

FIDDLE #2

如果你比较两个版本的输出,你可以看到 #1 会

If you compare the output of both versions, you can see that #1 will

start ...
many times sleeping
end ...

和#2

start...
1000
end
many times the delta

这是想要阻塞实际上是指.while 循环将尽可能多地运行并阻塞线程,而 #2 使用一个计时器,它将尽可能频繁地调用 loop,但每秒最多调用 60 次.

This is want blocking is actually referring to. The while loop will run with as much cycles as it can and blocks the thread, while #2 uses a timer, which will call loop as often as possible, but with a maximum of 60 times per second.

更新

参考评论:»如何查看计数« 如果您使用方法 #1,那么您永远不会看到它,因为:while 循环将消耗所有可用的 CPU 周期并运行直到时间到.在此期间,它会更新内部 HTML,但由于此循环阻塞了 UI,因此浏览器没有机会实际呈现结果,您最终会呈现结果.换句话说:您根本无法像 CPU 一样快速地更新 UI.

Referring to the comment: »How to see it counting« If you are using method #1, than you wont ever see it, because: The while loop will consume all available CPU cycles and runs until time is up. During that it updates the inner HTML, but since this loop block the UI, the Browser has no chance to actually render the result and you will end up with the result rendered. In other words: You simply cannot update the UI as fast as your CPU.

要查看您需要使用方法 #2 的任何内容,这样 UI 不会被阻塞,因为 requestAnimationFrame 要求浏览器在浏览器的渲染周期之间尽可能频繁地运行回调,这就是为什么每秒最多有 60 帧,因为这是浏览器的最大更新速率.如果您的回调时间超过 1000/60 毫秒,帧率会相应降低.

To see anything you need to use method #2, this way the UI is not blocked, because requestAnimationFrame asks the browser to run the callback as often as possible in between the render cycles of the browser, that is why there is a maximum of 60 Frames per Second, because this is the maximum update rate of the browser. If your callback takes longer than 1000/60ms the frame rate decreases accordingly.

如果您想显示浏览器在一个 Interval 中可以运行多少个周期,您需要一种不同的方法,可能是 Web Worker.有了它,您可以创建第二个线程,它不会干扰 UI.您可以在其中计算迭代次数,并在 »UI« 线程中,您可以从工作线程中提取该值并在每个动画帧中显示它.

If you want to display how many cycles the browser can run in a Interval, you need a different approach, which could be a Web Worker. With that, you can create a second thread, which wont interfere with the UI. Therein you can count the iterations and within the »UI« thread, you can pull that value from the worker and display it each animation Frame.

请注意 JS 是单线程的,当这个线程正在处理任何事情时,UI 会挂起并且不会更新,直到窗口»无响应脚本...« 弹出并要求您停止它.

Please not that JS is single threaded and while this thread is processing anything, the UI hangs and wont be updated until the window »unresponsive script…« pop up and asks you to stop it.

使用下面的代码,您可能会得到接近真实"迭代次数的计数.它计算固定的帧长度,更新 html,然后让浏览器进行渲染,同时暂停计算周期.所以这将比浏览器实际可以计算的周期更少.

With the code below you might get a count close to the »real« count of iterations. It counts for a fixed frame length, updates the html and than let the browser do the rendering, while counting the cycles is paused. So that will count less cycles than browser actually can.

function displayCount(duration){
    var end = new Date().getTime() + duration,
        cycles = 0,
        frame = 1000/30; //30fps

    (function loop(){
        var now = new Date().getTime(),
            countend = now + frame;

        while(new Date().getTime() < countend) {
           cycles++;
        }

        //UPDATE HTML here

        if(now < end) {
            window.requestAnimationFrame(loop);
        }

    })();
}

FIDDLE #3

这篇关于如何制作一个计数 3 秒的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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