javascript 一段时间后如何执行函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15896810/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 02:30:16  来源:igfitidea点击:

How to execute a function after some time

javascript

提问by Rayan Sp

I want to write a javascript code where I can execute a function after exactly 30 minutes.

我想编写一个 javascript 代码,我可以在 30 分钟后执行一个函数。

say I have a function called getScoreand another function called getResult. I want those functions to be executed after exactly thirty minutes.

说我有一个调用的函数getScore和另一个调用的函数getResult。我希望这些函数在 30 分钟后执行。

It's for a quiz purpose, the quiz duration is thirty minutes, so after the time passes, both functions should be executed.

以测验为目的,测验时长为三十分钟,所以时间过去后,应执行这两个功能。

回答by stef

You should use setTimeout():

你应该使用setTimeout()

setTimeout(function() {
    getScore(); 
    getResult(); 
}, 1800000);

The '1800000' is the time in milliseconds after which you want this function to execute. In this case, 30 minutes.

'1800000' 是您希望此函数执行的时间(以毫秒为单位)。在这种情况下,30 分钟。

回答by Agiel

If You Want To Show Element ,you can use This Code , This Will Show Button.

如果你想显示元素,你可以使用这个代码,这将显示按钮。

     function myFunc(){
        var linkEd = document.getElementById("buttonID");
        var timing = 6;
        var text_timing = document.createElement("span");
        linkEd.parentNode.replaceChild(text_timing, linkEd);
        var id;
        id = setInterval(function() {timing--;
      if (timing < 0) {
        clearInterval(id);
       text_timing.parentNode.replaceChild(linkEd, text_timing);
      } else {
       text_timing.innerHTML = "<h3 class='yourclass'>Button will appear after  <strong>" + timing.toString() + "</strong>  second</h3>";
      linkEd.style.display = "inline";
      }
    }, 1000);
}

This Is To Showing Time miliseconds

<h3 class='yourclass'>Button will appear after <strong>" + timing.toString() + " </strong> second</h3>

这是显示时间毫秒

<h3 class='yourclass'>按钮将在 <strong>" + Timing.toString() + " </strong> 秒后出现</h3>



To Call Time And show Button Use onclick event to show button after time 0

<button class='yourclass' onclick='myFunc()' id='button'>show time</button>

use display noneto hide the button

<button style='display:none' id='buttonID' class='yourclass'>after time</button>

调用时间并显示按钮使用 onclick 事件在时间 0 后显示按钮

<button class='yourclass' onclick='myFunc()' id='button'>显示时间</button>

使用display none隐藏按钮

<button style='display:none' id='buttonID' class='yourclass'>时间之后</button>