gpt4 book ai didi

javascript - 每 15 秒运行一次 JavaScript 代码

转载 作者:行者123 更新时间:2023-12-01 02:14:00 25 4
gpt4 key购买 nike

我一直在尝试使用 jQuery 在我的网页中显示随机引用。但是 while(true) { } 方法并没有解决我的问题,但是当我搜索了一下后,我发现不推荐这样做。

我有一个包含一些字符串的 JavaScript 数组。

var quotes = new Array();
quotes[0] = "string 1";
quotes[1] = "string 2";
quotes[2] = "string 3";
quotes[3] = "string 4";

这段代码运行良好:

$(function() {
var random_quote = quotes[Math.floor(Math.random() * quotes.length)];
var $rand = $('div#randomQuote');
$rand.append(random_quote);
$rand.hide();
$rand.fadeIn("500");
});

但是,我尝试每 15 秒运行一次以更新报价。

正如我所说,我尝试过 while true 循环和 sleep 功能,但它不起作用。

我怎样才能实现这个目标?

最佳答案

使用setInterval

setInterval(yourFunction, timeInMilliseconds);
<小时/>
function randomQuote () {
var random_quote = quotes[Math.floor(Math.random() * quotes.length)];
var $rand = $('div#randomQuote');
$rand.append(random_quote);
$rand.hide();
$rand.fadeIn("500");
}

$(function () {
setInterval(randomQuote, 15000);
});

关于javascript - 每 15 秒运行一次 JavaScript 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9340654/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com