Javascript中的同步睡眠功能 [英] Synchronous Sleep function in Javascript

查看:129
本文介绍了Javascript中的同步睡眠功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用JS / JQuery模拟进度条,这是我的HTML代码:

I want to simulate a progress bar using JS/JQuery, this is my HTML code :

<p id="percentage">0%</p>

我想从0变为100并且看到-Visually-慢动作的进展,那么什么我需要的是一个For循环和一个暂停函数,但遗憾的是在中没有类似睡眠的函数Javascript

I want to go from 0 to 100 and see -Visually- the progress in slow motion, So What I need exactly is a For Loop and a pause function, but unfortunately there is no sleep-like function in Javascript

在做了一些研究之后,我在 Jquery中找到了 setTimeOut 函数,你可以在这里找到 Javascript 代码:

After doing some research, I found the setTimeOut function in Jquery, you can find herein the Javascript code :

for (i = 0; i < 100; i++) { 
    setTimeout(function() {
        $("#percentage").text(i+"%");
    }, 1000);
} 

但不太可能,这不起作用,因为根据文档 setTimeout 函数是异步的, Javascript 的执行将继续。这意味着没有类似暂停的行为,进度条将在1000ms后从0变为100,而不是从0变为1.

But unlikely, this won't work, because according to the documentation the setTimeout function is asynchronous, and the execution of the Javascript will continue. That means that there is no pause-like behavior, and the progress bar will go from 0 to 100 after 1000ms instead of going from 0 to 1.

虽然setTimeout无法解决我的问题,但我尝试实现自己的sleep()函数,这里是:

While setTimeout can't solve my problem, I tried to implement my own sleep() function, and here it is :

function sleep(ms){
    var waitTimeInMilliseconds = new Date().getTime() + ms;
    while(new Date().getTime() < waitTimeInMilliseconds ) true;
}

虽然我认为这是这个场景的银弹 - 它是一个坏主意,我知道 - 我很惊讶,因为这种方法也没有解决我的问题,并且在睡眠时间界面仍然处于闲置状态(我无法点击,选择或在我的HTML页面中执行任何操作)。

While I was thinking that this is the silver bullet to this scenario -It was a bad Idea, I know-, I was surprised since also this approach didn't solve my problem, and the interface remains Idle during the sleep time, (I cannot click, select or do anything in my HTML page).

如何解决这个问题?

推荐答案

你可能想要一些东西有点像这样使用 setInterval

You'd probably want something a bit like this using setInterval:

var i = 0;
var intervalId;
intervalId = setInterval(function() {
    $("#pourcentage").text(i+"%");
    if(i >= 100){
        clearInterval(intervalId);
    }
    i++;
}, 1000);

或使用 setTimeout

var i = 0;
var scheduleNextTimeout; 
scheduleNextTimeout = function(){
    setTimeout(function() {
        $("#pourcentage").text(i+"%");
        if(i < 100){
            scheduleNextTimeout();
        }
        i++;
    }, 1000);
};
scheduleNextTimeout();

这篇关于Javascript中的同步睡眠功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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