使用JavaScript执行特定延迟后的脚本

时间:2022-06-02 00:11:53

Is there any JavaScript method similar to the jQuery delay() or wait() (to delay the execution of a script for a specific amount of time)?

有类似jQuery delay()或wait()的JavaScript方法吗?

12 个解决方案

#1


155  

There is the following:

有以下几点:

setTimeout(function, milliseconds);

function which can be passed the time after which the function will be executed.

函数,该函数可以在执行后的时间内传递。

See: Window setTimeout() Method.

看到:窗口setTimeout()方法。

#2


212  

Just to add to what everyone else have said about setTimeout: If you want to call a function with a parameter in the future, you need to set up some anonymous function calls.

再补充一下大家对setTimeout的看法:如果将来想调用一个带有参数的函数,需要设置一些匿名函数调用。

You need to pass the function as an argument for it to be called later. In effect this means without brackets behind the name. The following will call the alert at once, and it will display 'Hello world':

您需要将函数作为参数传递,以便稍后调用它。实际上,这意味着名字后面没有括号。以下将立即调用警报,并显示“Hello world”:

var a = "world";
setTimeout(alert("Hello " + a), 2000);

To fix this you can either put the name of a function (as Flubba has done) or you can use an anonymous function. If you need to pass a parameter, then you have to use an anonymous function.

为了解决这个问题,您可以将一个函数的名称(如Flubba已经完成)或者您可以使用一个匿名函数。如果需要传递参数,则必须使用匿名函数。

var a = "world";
setTimeout(function(){alert("Hello " + a)}, 2000);
a = "Stack Overflow";

But if you run that code you will notice that after 2 seconds the popup will say 'Hello Stack Overflow'. This is because the value of the variable a has changed in those two seconds. To get it to say 'Hello world' after two seconds, you need to use the following code snippet:

但是如果你运行这段代码,你会注意到2秒后弹出窗口会显示“Hello Stack Overflow”。这是因为变量a的值在这两秒内发生了变化。要让它在两秒钟后发出“Hello world”,您需要使用以下代码片段:

function callback(a){
    return function(){
        alert("Hello " + a);
    }
}
var a = "world";
setTimeout(callback(a), 2000);
a = "Stack Overflow";

It will wait 2 seconds and then popup 'Hello world'.

它将等待2秒,然后弹出“Hello world”。

#3


32  

Just to expand a little... You can execute code directly in the setTimeout call, but as @patrick says, you normally assign a callback function, like this. The time is milliseconds

只是稍微膨胀一下……您可以在setTimeout调用中直接执行代码,但是正如@patrick所说,您通常会分配一个回调函数,如下所示。时间是毫秒

setTimeout(func, 4000);
function func() {
    alert('Do stuff here');
}

#4


24  

If you really want to have a blocking (synchronous) delay function (for whatsoever), why not do something like this:

如果您真的想要一个阻塞(同步)延迟函数(无论如何),为什么不做如下的事情:

<script type="text/javascript">
    function delay(ms) {
        var cur_d = new Date();
        var cur_ticks = cur_d.getTime();
        var ms_passed = 0;
        while(ms_passed < ms) {
            var d = new Date();  // Possible memory leak?
            var ticks = d.getTime();
            ms_passed = ticks - cur_ticks;
            // d = null;  // Prevent memory leak?
        }
    }

    alert("2 sec delay")
    delay(2000);
    alert("done ... 500 ms delay")
    delay(500);
    alert("done");
</script>

#5


13  

You can also use window.setInterval() to run some code repeatedly at a regular interval.

您还可以使用windows . setinterval()在一个常规的间隔内重复地运行一些代码。

#6


13  

You need to use setTimeout and pass it a callback function. The reason you can't use sleep in javascript is because you'd block the entire page from doing anything in the meantime. Not a good plan. Use Javascript's event model and stay happy. Don't fight it!

您需要使用setTimeout并向它传递一个回调函数。不能在javascript中使用sleep是因为在此期间会阻止整个页面执行任何操作。不是一个好计划。使用Javascript的事件模型并保持愉快。别打架!

#7


10  

If you only need to test a delay you can use this:

如果你只需要测试一个延迟,你可以使用以下方法:

function delay(ms) {
   ms += new Date().getTime();
   while (new Date() < ms){}
}

And then if you want to delay for 2 second you do:

如果你想延迟2秒,你可以这样做:

delay(2000);

Might not be the best for production though. More on that in the comments

但这可能不是最好的产品。更多信息请见评论

#8


9  

To add on the earlier comments, I would like to say the following :

为了补充先前的评论,我想说:

The setTimeout() function in JavaScript does not pause execution of the script per se, but merely tells the compiler to execute the code sometime in the future.

JavaScript中的setTimeout()函数本身不会暂停脚本的执行,只是告诉编译器在将来某个时候执行代码。

There isn't a function that can actually pause execution built into JavaScript. However, you can write your own function that does something like an unconditional loop till the time is reached by using the Date() function and adding the time interval you need.

实际上,没有一个函数可以在JavaScript中暂停执行。但是,您可以编写自己的函数,它执行一些类似于无条件循环的操作,直到使用Date()函数并添加所需的时间间隔为止。

#9


2  

The simple reply is:

简单的回答是:

setTimeout(
    function () {
        x = 1;
    }, 1000);

The function above waits for 1 second (1000 ms) then sets x to 1. Obviously this is an example; you can do anything you want inside the anonymous function.

上面的函数等待1秒(1000毫秒),然后将x设置为1。显然这是一个例子;您可以在匿名函数中执行任何需要的操作。

#10


1  

why can't you put the code behind a promise? (typed in off the top of my head)

你为什么不把代码放在承诺后面呢?(从我头顶上敲下来)

new Promise(function(resolve, reject) {
  setTimeout(resolve, 2000);
}).then(function() {
  console.log('do whatever you wanted to hold off on');
});

#11


1  

I really liked Maurius' explanation (highest upvoted response) with the three different methods for calling setTimeout.

我真的很喜欢Maurius的解释(最高向上的响应),使用三种调用setTimeout的不同方法。

In my code I want to automatically auto-navigate to the previous page upon completion of an AJAX save event. The completion of the save event has a slight animation in the CSS indicating the save was successful.

在我的代码中,我希望在AJAX保存事件完成时自动导航到上一个页面。保存事件的完成在CSS中有一个小动画,指示保存成功。

In my code I found a difference between the first two examples:

在我的代码中,我发现了前两个例子之间的差异:

setTimeout(window.history.back(), 3000);

This one does not wait for the timeout--the back() is called almost immediately no matter what number I put in for the delay.

这个并不等待超时——无论我输入什么数字来延迟,back()几乎都会立即调用。

However, changing this to:

然而,改变这种:

setTimeout(function() {window.history.back()}, 3000);

This does exactly what I was hoping.

这正是我所希望的。

This is not specific to the back() operation, the same happens with alert(). Basically with the alert() used in the first case, the delay time is ignored. When I dismiss the popup the animation for the CSS continues.

这不是back()操作特有的,alert()也是如此。基本上,在第一种情况中使用alert(),可以忽略延迟时间。当我关闭弹出窗口时,CSS的动画将继续。

Thus, I would recommend the second or third method he describes even if you are using built in functions and not using arguments.

因此,我推荐他描述的第二或第三种方法,即使您使用的是内置函数,而不是参数。

#12


0  

I had some ajax commands I wanted to run with a delay in between. Here is a simple example of one way to do that. I am prepared to be ripped to shreds though for my unconventional approach. :)

我有一些ajax命令,我想在这之间运行一个延迟。这里有一个简单的例子。我准备被撕成碎片,尽管我的非常规方法。:)

//  Show current seconds and milliseconds
//  (I know there are other ways, I was aiming for minimal code
//  and fixed width.)
function secs()
{
    var s = Date.now() + ""; s = s.substr(s.length - 5);
  return s.substr(0, 2) + "." + s.substr(2);
}

//  Log we're loading
console.log("Loading: " + secs());

//  Create a list of commands to execute
var cmds = 
[
    function() { console.log("A: " + secs()); },
    function() { console.log("B: " + secs()); },
    function() { console.log("C: " + secs()); },
    function() { console.log("D: " + secs()); },
    function() { console.log("E: " + secs()); },
  function() { console.log("done: " + secs()); }
];

//  Run each command with a second delay in between
var ms = 1000;
cmds.forEach(function(cmd, i)
{
    setTimeout(cmd, ms * i);
});

// Log we've loaded (probably logged before first command)
console.log("Loaded: " + secs());

You can copy the code block and paste it into a console window and see something like:

您可以复制代码块并将其粘贴到控制台窗口,然后看到如下内容:

Loading: 03.077
Loaded: 03.078
A: 03.079
B: 04.075
C: 05.075
D: 06.075
E: 07.076
done: 08.076

#1


155  

There is the following:

有以下几点:

setTimeout(function, milliseconds);

function which can be passed the time after which the function will be executed.

函数,该函数可以在执行后的时间内传递。

See: Window setTimeout() Method.

看到:窗口setTimeout()方法。

#2


212  

Just to add to what everyone else have said about setTimeout: If you want to call a function with a parameter in the future, you need to set up some anonymous function calls.

再补充一下大家对setTimeout的看法:如果将来想调用一个带有参数的函数,需要设置一些匿名函数调用。

You need to pass the function as an argument for it to be called later. In effect this means without brackets behind the name. The following will call the alert at once, and it will display 'Hello world':

您需要将函数作为参数传递,以便稍后调用它。实际上,这意味着名字后面没有括号。以下将立即调用警报,并显示“Hello world”:

var a = "world";
setTimeout(alert("Hello " + a), 2000);

To fix this you can either put the name of a function (as Flubba has done) or you can use an anonymous function. If you need to pass a parameter, then you have to use an anonymous function.

为了解决这个问题,您可以将一个函数的名称(如Flubba已经完成)或者您可以使用一个匿名函数。如果需要传递参数,则必须使用匿名函数。

var a = "world";
setTimeout(function(){alert("Hello " + a)}, 2000);
a = "Stack Overflow";

But if you run that code you will notice that after 2 seconds the popup will say 'Hello Stack Overflow'. This is because the value of the variable a has changed in those two seconds. To get it to say 'Hello world' after two seconds, you need to use the following code snippet:

但是如果你运行这段代码,你会注意到2秒后弹出窗口会显示“Hello Stack Overflow”。这是因为变量a的值在这两秒内发生了变化。要让它在两秒钟后发出“Hello world”,您需要使用以下代码片段:

function callback(a){
    return function(){
        alert("Hello " + a);
    }
}
var a = "world";
setTimeout(callback(a), 2000);
a = "Stack Overflow";

It will wait 2 seconds and then popup 'Hello world'.

它将等待2秒,然后弹出“Hello world”。

#3


32  

Just to expand a little... You can execute code directly in the setTimeout call, but as @patrick says, you normally assign a callback function, like this. The time is milliseconds

只是稍微膨胀一下……您可以在setTimeout调用中直接执行代码,但是正如@patrick所说,您通常会分配一个回调函数,如下所示。时间是毫秒

setTimeout(func, 4000);
function func() {
    alert('Do stuff here');
}

#4


24  

If you really want to have a blocking (synchronous) delay function (for whatsoever), why not do something like this:

如果您真的想要一个阻塞(同步)延迟函数(无论如何),为什么不做如下的事情:

<script type="text/javascript">
    function delay(ms) {
        var cur_d = new Date();
        var cur_ticks = cur_d.getTime();
        var ms_passed = 0;
        while(ms_passed < ms) {
            var d = new Date();  // Possible memory leak?
            var ticks = d.getTime();
            ms_passed = ticks - cur_ticks;
            // d = null;  // Prevent memory leak?
        }
    }

    alert("2 sec delay")
    delay(2000);
    alert("done ... 500 ms delay")
    delay(500);
    alert("done");
</script>

#5


13  

You can also use window.setInterval() to run some code repeatedly at a regular interval.

您还可以使用windows . setinterval()在一个常规的间隔内重复地运行一些代码。

#6


13  

You need to use setTimeout and pass it a callback function. The reason you can't use sleep in javascript is because you'd block the entire page from doing anything in the meantime. Not a good plan. Use Javascript's event model and stay happy. Don't fight it!

您需要使用setTimeout并向它传递一个回调函数。不能在javascript中使用sleep是因为在此期间会阻止整个页面执行任何操作。不是一个好计划。使用Javascript的事件模型并保持愉快。别打架!

#7


10  

If you only need to test a delay you can use this:

如果你只需要测试一个延迟,你可以使用以下方法:

function delay(ms) {
   ms += new Date().getTime();
   while (new Date() < ms){}
}

And then if you want to delay for 2 second you do:

如果你想延迟2秒,你可以这样做:

delay(2000);

Might not be the best for production though. More on that in the comments

但这可能不是最好的产品。更多信息请见评论

#8


9  

To add on the earlier comments, I would like to say the following :

为了补充先前的评论,我想说:

The setTimeout() function in JavaScript does not pause execution of the script per se, but merely tells the compiler to execute the code sometime in the future.

JavaScript中的setTimeout()函数本身不会暂停脚本的执行,只是告诉编译器在将来某个时候执行代码。

There isn't a function that can actually pause execution built into JavaScript. However, you can write your own function that does something like an unconditional loop till the time is reached by using the Date() function and adding the time interval you need.

实际上,没有一个函数可以在JavaScript中暂停执行。但是,您可以编写自己的函数,它执行一些类似于无条件循环的操作,直到使用Date()函数并添加所需的时间间隔为止。

#9


2  

The simple reply is:

简单的回答是:

setTimeout(
    function () {
        x = 1;
    }, 1000);

The function above waits for 1 second (1000 ms) then sets x to 1. Obviously this is an example; you can do anything you want inside the anonymous function.

上面的函数等待1秒(1000毫秒),然后将x设置为1。显然这是一个例子;您可以在匿名函数中执行任何需要的操作。

#10


1  

why can't you put the code behind a promise? (typed in off the top of my head)

你为什么不把代码放在承诺后面呢?(从我头顶上敲下来)

new Promise(function(resolve, reject) {
  setTimeout(resolve, 2000);
}).then(function() {
  console.log('do whatever you wanted to hold off on');
});

#11


1  

I really liked Maurius' explanation (highest upvoted response) with the three different methods for calling setTimeout.

我真的很喜欢Maurius的解释(最高向上的响应),使用三种调用setTimeout的不同方法。

In my code I want to automatically auto-navigate to the previous page upon completion of an AJAX save event. The completion of the save event has a slight animation in the CSS indicating the save was successful.

在我的代码中,我希望在AJAX保存事件完成时自动导航到上一个页面。保存事件的完成在CSS中有一个小动画,指示保存成功。

In my code I found a difference between the first two examples:

在我的代码中,我发现了前两个例子之间的差异:

setTimeout(window.history.back(), 3000);

This one does not wait for the timeout--the back() is called almost immediately no matter what number I put in for the delay.

这个并不等待超时——无论我输入什么数字来延迟,back()几乎都会立即调用。

However, changing this to:

然而,改变这种:

setTimeout(function() {window.history.back()}, 3000);

This does exactly what I was hoping.

这正是我所希望的。

This is not specific to the back() operation, the same happens with alert(). Basically with the alert() used in the first case, the delay time is ignored. When I dismiss the popup the animation for the CSS continues.

这不是back()操作特有的,alert()也是如此。基本上,在第一种情况中使用alert(),可以忽略延迟时间。当我关闭弹出窗口时,CSS的动画将继续。

Thus, I would recommend the second or third method he describes even if you are using built in functions and not using arguments.

因此,我推荐他描述的第二或第三种方法,即使您使用的是内置函数,而不是参数。

#12


0  

I had some ajax commands I wanted to run with a delay in between. Here is a simple example of one way to do that. I am prepared to be ripped to shreds though for my unconventional approach. :)

我有一些ajax命令,我想在这之间运行一个延迟。这里有一个简单的例子。我准备被撕成碎片,尽管我的非常规方法。:)

//  Show current seconds and milliseconds
//  (I know there are other ways, I was aiming for minimal code
//  and fixed width.)
function secs()
{
    var s = Date.now() + ""; s = s.substr(s.length - 5);
  return s.substr(0, 2) + "." + s.substr(2);
}

//  Log we're loading
console.log("Loading: " + secs());

//  Create a list of commands to execute
var cmds = 
[
    function() { console.log("A: " + secs()); },
    function() { console.log("B: " + secs()); },
    function() { console.log("C: " + secs()); },
    function() { console.log("D: " + secs()); },
    function() { console.log("E: " + secs()); },
  function() { console.log("done: " + secs()); }
];

//  Run each command with a second delay in between
var ms = 1000;
cmds.forEach(function(cmd, i)
{
    setTimeout(cmd, ms * i);
});

// Log we've loaded (probably logged before first command)
console.log("Loaded: " + secs());

You can copy the code block and paste it into a console window and see something like:

您可以复制代码块并将其粘贴到控制台窗口,然后看到如下内容:

Loading: 03.077
Loaded: 03.078
A: 03.079
B: 04.075
C: 05.075
D: 06.075
E: 07.076
done: 08.076