更快的JavaScript处理 [英] Faster javascript processing

查看:88
本文介绍了更快的JavaScript处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

刚问了我的第一个问题并得到了很好的回应。非常有帮助。帮我创建了这个javascript,在同一页面上创建了两个随机数。

Just asked my first question and got a great response. So helpful. Helped me create this bit of javascript to create two random numbers on the same page.

<script>
window.onload = function(){
generateRandomNumber1();
generateRandomNumber2();
}</script>

<script>
function generateRandomNumber1(){
var n = 30;
var number = Math.floor(Math.random()*n)+1;
document.getElementById("random1").innerHTML = number;
}

function generateRandomNumber2(){
var n = 15;
var number = Math.floor(Math.random()*n)+1;
document.getElementById("random2").innerHTML = number;
}
</script>

A也使用这段脚本来显示延时的两个div:

A also use this bit of script to show the two divs on a time delay:

<script>
var toggle = function() {
$("#loadingContainer1").show();
}
setTimeout(toggle, 1000);
</script>
<script>
var toggle = function() {
$("#loadingContainer1").hide();
}
setTimeout(toggle, 8000);
</script> 
<script>
var toggle = function() {
$("#loadingContainer2").show();
}
setTimeout(toggle, 7000);
</script> 
<script>
var toggle = function() {
$("#loadingContainer2").hide();
}
setTimeout(toggle, 14000);
</script> 

我知道这真的很麻烦,但它很有效,而且我对自己工作最满意我自己(在Stack Overflow上得到了很多其他人的帮助)。

Really cumbersome, I know, but it works, and I'm quite pleased with myself for working most of this out myself (with a lot of help from other people's threads on Stack Overflow).

无论如何,一切正常,所以这不是我的问题,唯一问题是,随机数发生器工作得如此缓慢,以至于数字出现的div通常在产生随机数之前来去匆匆。在我刷新页面几次之后,它们通常开始工作得更快,但是有没有什么方法可以加快这个过程,所以随机数会在页面加载的第一秒内生成。

Anyway, it all works, so that isn't my issue, the only problem is, that the random number generator works so slowly, that the divs the numbers appear in have usually come and gone before the random numbers are generated. After I refresh the page a couple of times, they normally start working a bit faster, but is there any way I could speed up the process so the random numbers are generated within the first second of the page loading.

非常感谢。

推荐答案

那里有很多乱码,但也许是因为 onload 在页面完全加载之前不会触发,因为它很慢。以下是重写您的代码以更好地工作:

There is a LOT of messy code there, but maybe it's because onload doesn't fire until the page has completely loaded that it's slow. Here's a rewrite of your code to work better:

<script type="text/javascript">
    $(function() { // uses jQuery's "ready" handler
        $("#random1").html(Math.floor(Math.random()*30)+1);
        $("#random2").html(Math.floor(Math.random()*15)+1);
        $("#loadingContainer1").delay(1000).fadeIn(0).delay(7000).fadeOut(0);
        $("#loadingContainer2").delay(7000).fadeIn(0).delay(7000).fadeOut(0);
    });
</script>

希望这有帮助!

这篇关于更快的JavaScript处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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