在 jQuery 中按时间间隔运行函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6081443/
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-08-26 20:21:55  来源:igfitidea点击:

Run a function in time interval in jQuery

jqueryintervals

提问by Sesen

I want to make a banner by using jQuery. When the page loaded script will show a group of photos one by one. For example, the controller sends 10 photos and each photo will be shown in 30 seconds after 10 minutes the script demand another photo from the controller.

我想使用 jQuery 制作横幅。当页面加载脚本时,会一张一张显示一组照片。例如,控制器发送 10 张照片,每张照片将在 10 分钟后的 30 秒内显示,脚本要求控制器发送另一张照片。

The question is: How can I make a function that runs in 30 sec. I need to run a function in a time interval without any button click or anything else.

问题是:如何制作一个在 30 秒内运行的函数。我需要在没有任何按钮点击或其他任何东西的时间间隔内运行一个函数。

回答by Roki

The main method is:

主要方法是:

 setInterval(function () {
        console.log('it works' + new Date());
    },30000);

If you need to clear interval in future:

如果您将来需要清除间隔:

var myInterval = setInterval(function () {
            console.log('it works' + new Date());
        },30000); 

in the future:

在将来:

clearInterval(myInterval);

回答by yckart

Try something like this:

尝试这样的事情:

HTML:

HTML:

<ul id="ticker">
    <li>Image 1</li>
    <li>Image 2</li>
    <li>Image 3</li>
    <li>Image 4</li>
    <li>Image 5</li>
</ul>?

CSS:

CSS:

ul{height:20px; overflow:auto}?

JS:

JS:

var $ticker = $('ul#ticker');
var speed = 300;
var pause = 3000;

var tick = function () {
    var first = $ticker.find('li').first().animate({
        height: 0
    }, speed).hide('normal', function() {
        $(this).remove();
        $ticker.append('<li>' + first + '</li>');
    }).html();
};

$('ul#ticker').click(tick);
setInterval(tick, pause);

Here, a simple Demo.

在这里,一个简单的Demo

回答by BnW

JavaScript provides a setTimeoutfunction:

JavaScript 提供了一个setTimeout函数

var timeoutID = window.setTimeout(code, delay);

回答by jams

You should use setIntervallike this

你应该setInterval像这样使用

setInterval( "alert('Hello')", 5000 );