Javascript 在 jQuery 中使用 setInterval 调用函数?

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

Call function with setInterval in jQuery?

javascriptjquery

提问by 3D-kreativ

I'm trying to create a interval call to a function in jQuery, but it doesn't work! My first question is, can I mix common JavaScript with jQuery?

我正在尝试在 jQuery 中创建对函数的间隔调用,但它不起作用!我的第一个问题是,我可以将常见的 JavaScript 与 jQuery 混合使用吗?

Should I use setInterval("test()",1000);or something like this:

我应该使用setInterval("test()",1000);或类似的东西:

var refreshId = setInterval(function(){
    code...
}, 5000);

Where do I put the function that I call and how do I activate the interval? Is it a difference in how to declare a function in JavaScript compared to jQuery?

我在哪里放置我调用的函数以及如何激活间隔?与 jQuery 相比,如何在 JavaScript 中声明函数有区别吗?

回答by Lightness Races in Orbit

To write the best code, you "should" use the latter approach, with a function reference:

要编写最好的代码,您“应该”使用后一种方法,并带有函数引用:

var refreshId = setInterval(function() {}, 5000);

or

或者

function test() {}
var refreshId = setInterval(test, 5000);

but your approach of

但你的方法

function test() {}
var refreshId = setInterval("test()", 5000);

is basically valid, too (as long as test()is global).

基本上也是有效的(只要test()是全局的)。

Note that there is no such thing really as "in jQuery". You're still writing the Javascript language; you're just using some pre-made functions that are the jQuery library.

请注意,实际上没有“在 jQuery 中”这样的东西。您仍在编写 Javascript 语言;你只是在使用一些 jQuery 库的预制函数。

回答by ayk

First of all: Yes you can mix jQuery with common JS :)

首先:是的,您可以将 jQuery 与普通 JS 混合使用 :)

Best way to build up an intervall call of a function is to use setTimeout methode:

建立函数的间隔调用的最佳方法是使用 setTimeout 方法:

For example, if you have a function called test() and want to repeat it all 5 seconds, you could build it up like this:

例如,如果您有一个名为 test() 的函数并希望将其全部重复 5 秒,您可以像这样构建它:

function test(){
    console.log('test called');
    setTimeout(test, 5000);
}

Finally you have to trigger the function once:

最后你必须触发一次函数:

$(document).ready(function(){
    test();
});

This document ready function is called automatically, after all html is loaded.

在加载所有 html 后,将自动调用此文档就绪函数。

回答by jm_toball

jQuery is just a set of helpers/libraries written in Javascript. You can still use all Javascript features, so you can call whatever functions, also from inside jQuery callbacks. So both possibilities should be okay.

jQuery 只是一组用 Javascript 编写的帮助程序/库。您仍然可以使用所有 Javascript 功能,因此您可以调用任何函数,也可以从 jQuery 回调内部调用。所以这两种可能性都应该没问题。

回答by vidur punj

setInterval(function() {
    updatechat();
}, 2000);

function updatechat() {
    alert('hello world');
}