setTimeout() を使用して jQuery(document).ready の外部で関数を呼び出す方法は?
-
21-09-2019 - |
質問
私のコードは次のようになります:
$(document).ready(function(){
var cont = 0;
function func1(cont)
{
//Some code here
search.setSearchCompleteCallback(this, searchComplete, null);
//Some other code
}
func1(cont);
function searchComplete()
{
//Some code
cont += 1;
if (cont < length ) {
func1(cont);
} else {
// Other code
}
}
});
したがって、私がやりたいのは、 func1(cont) の実行を遅らせることです。searchComplete() 関数内。その理由は、コードが行うのは Google 検索 API と PageRank チェックを操作することだけであり、禁止されないようにスクリプトの速度を下げる必要があるためです。(特に PR チェックに関して行われるリクエストについて)。単純に func1(cont) で setTimeout() を使用すると、func1() が定義されていないと表示されます。$(document).ready() の外で関数を取得しようとすると、関数が表示されますが、ページを完全にロードする必要があるため、Google コードはそれを実行しません。
setTimeout を修正するにはどうすればよいですか、またはスクリプトを数秒間一時停止するにはどうすればよいですか?
ありがとう!
解決
書き込み
func1(cont);
タグなど
window.setTimeout(function() {
func1(cont);
}, 1000);
他のヒント
代わりに、このような関数を宣言する
function func1(cont) {}
このようにそれを宣言します:
var func1 = function(cont) {}
あなたはあなたのコードを再配置する必要があります少します:
$(document).ready(function(){
var cont = 0;
var func1;
var searchComplete = function()
{
//Some code
cont += 1;
if (cont < length ) {
func1(cont);
} else {
// Other code
}
}
func1 = function(cont)
{
//Some code here
search.setSearchCompleteCallback(this, searchComplete, null);
//Some other code
}
func1(cont);
});
私はこのような何かを試してみました。私はjqueryの名前空間内のVARSや関数を宣言することを好むが、あなたは同様に続き、変数や文書レディ機能の外で機能を移動し、それらに利用できるグローバルを持っている可能性があります。
$(document).ready(function(){
$.cont = 0;
$.func1 = function() {
//Some code here
search.setSearchCompleteCallback(this, $.searchComplete, null);
//Some other code
}
$.searchComplete = function() {
//Some code
$.cont += 1;
if (cont < length ) {
setTimeout($.func1,1000);
} else {
// Other code
}
}
setTimeout($.func1,1000); // delay the initial start by 1 second
});
あなたの説明が正しいことを願っています:
- document.ready() イベントが発生する
- document.ready() 内で X ミリ秒後に関数を呼び出す必要がある
- この関数は、Google オブジェクトの search.setSearchCompleteCallback() を別の関数に接続します (この関数には、
this
)
この場合、document.ready() スコープ内で関数を宣言する必要があるのはなぜでしょうか?単純に 3 つすべてをグローバルにすることはできないでしょうか?例えば
var search = null; // initialise the google object
var cont = 0;
function timedSearch()
{
search.setSearchCompleteCallback(this, searchComplete, null);
}
function searchComplete()
{
if (++cont < length) // postfix it below if this is wrong
setTimeout(timedSearch,1000);
}
$(document).ready(function()
{
setTimeout(timedSearch,1000);
}
私が誤解していたら、反対票を投じてください。
所属していません StackOverflow