在Javascript中一个接一个地执行一个函数

Executing one function after the other in Javascript

本文关键字:一个 执行 函数 Javascript      更新时间:2023-09-26

由于某种原因,我最难理解javascript回调,这让我很头疼。我有三个函数,我正试图用它们来解析来自这样一个网站的一些数据——

function parseText() {
    //this finds a bunch of DOM elements, grabs the innerHTML from each and stores
    //it in an array
}
function scrollToTop() {
    //this scrolls to the top of the window where I'm getting text from,
    //which causes the window to load more DOM elements to parse
}
function removeOldElements() {
    //this removes the already-parsed DOM elements from the DOM
}

我一直这样称呼它。。我现在意识到这是一种非常可怕的做法,因为我一切换标签,Chrome就会完全打乱setTimeoutsetInterval的计时,并导致很多错误。。

function doEverything() {
    parseText();
    setTimeout(scrollToTop, 2000);
    setTimeout(removeOldElements, 4000);
}
setInterval(doEverything, 5000); 
//this loops it every 5 seconds so I can just run it in a separate tab
//while I continue to work on other things

这有点。。但是setInterval中的任何暂停或中断都会破坏代码,我知道我应该对这类事情使用回调,以便在第一个执行完成后调用一个,但我似乎无法让它工作。

我一直在读关于回调的文章,但并不真正理解应该是什么格式。我尝试过这样的东西:

function parseText(callback) {
}
function scrollToTop(callback) {
}
function removeOldElements() {
}
function doEverything() {
    parseText(
        scrollToTop(
            removeOldElements
        )
    )
}
setInterval(doEverything, 5000);

但这似乎只调用了scrollToTopparseText两次。。并且根本不调用第三个函数<见鬼>现在我真的很困惑。。

有人能帮忙吗?我确信我在这里做了一些非常基本的完全错误的事情。。

您在谈论回调,但我没有看到任何关于代码的显式异步。这里需要区分两件事:

  1. 同步函数调用:主线程执行整个函数块,直到全部执行完毕才返回控制。这类事情不需要回调,只需内联调用函数即可

// some code func() // some more code`

  1. 异步函数,需要一些时间才能执行。为了不阻塞主线程(通常是UI线程本身),代码被推迟到稍后引擎可以腾出一些处理周期时。这是您需要回调的地方。它看起来是这样的:

// some code async_func(callback_func) // some more code

不能保证async_func中的所有代码都会在some more code之前执行。事实上,它很可能会在稍后执行。

从函数的名称来看,它们中似乎没有任何一个在做任何实际的异步工作。所以你可以这样称呼他们:

function doEverything() {
    parseText()
    scrollToTop()
    removeOldElements()
}

此外,您忘记了最后一个函数调用removeoldElements()的括号,这就是它没有执行的原因。

回调是一个不错的选择,此示例可能会进一步指导您。

function one(fn) {
  console.debug('one...');
  setTimeout(fn, 1000);
}
function two(fn) {
  console.debug('two...');
  setTimeout(fn, 1000);
}
function three(fn) {
  console.debug('three...');
  setTimeout(fn, 1000);
}
function loop() {
  console.debug('loop...');
  setTimeout(function() {
    one(function() {
      two(function() {
        three(loop);
      });
    });
  }, 1000);
}
setTimeout(loop, 1000);
Open browser console, for logs.

我不确定你想做什么,但我建议你这样做:

function parseText(callback) {
        //some code here
        console.log("parsetext");
        scrollToTop('callback');
}
function scrollToTop(callback) {
        //some code here
        console.log("scrollToTop");
        removeOldElements();
}
function removeOldElements() {
        //some code here
        console.log("removeOldElements");
        setTimeout(parseText, 5000);
}
ingparseText();