Как вызвать Последовательное Выполнение JavaScript?

Вот мой вклад C, взвешивающийся в 18 символах:

void o(){o();o();}

Это , партия тяжелее к последнему вызову оптимизирует!:-P

64
задан ROMANIA_engineer 23 June 2017 в 22:03
поделиться

3 ответа

Well, setTimeout, per its definition, will not hold up the thread. This is desirable, because if it did, it'd freeze the entire UI for the time it was waiting. if you really need to use setTimeout, then you should be using callback functions:

function myfunction() {
    longfunctionfirst(shortfunctionsecond);
}

function longfunctionfirst(callback) {
    setTimeout(function() {
        alert('first function finished');
        if(typeof callback == 'function')
            callback();
    }, 3000);
};

function shortfunctionsecond() {
    setTimeout('alert("second function finished");', 200);
};

If you are not using setTimeout, but are just having functions that execute for very long, and were using setTimeout to simulate that, then your functions would actually be synchronous, and you would not have this problem at all. It should be noted, though, that AJAX requests are asynchronous, and will, just as setTimeout, not hold up the UI thread until it has finished. With AJAX, as with setTimeout, you'll have to work with callbacks.

46
ответ дан 24 November 2019 в 15:57
поделиться

In javascript, there is no way, to make the code wait. I've had this problem and the way I did it was do a synchronous SJAX call to the server, and the server actually executes sleep or does some activity before returning and the whole time, the js waits.

Eg of Sync AJAX: http://www.hunlock.com/blogs/Snippets:_Synchronous_AJAX

1
ответ дан 24 November 2019 в 15:57
поделиться

В вашем примере первая функция фактически завершается до запуска второй функции. setTimeout не задерживает выполнение функции до тех пор, пока не истечет время ожидания, он просто запустит таймер в фоновом режиме и выполнит ваш оператор предупреждения по истечении указанного времени.

В JavaScript нет собственного способа выполнения "сна". Вы можете написать цикл, который проверяет время, но это создаст большую нагрузку на клиента. Вы также можете выполнить синхронный вызов AJAX, как описано в emacsian, но это создаст дополнительную нагрузку на ваш сервер. Лучше всего этого избежать, что в большинстве случаев должно быть достаточно просто, если вы поймете, как работает setTimeout.

1
ответ дан 24 November 2019 в 15:57
поделиться
Другие вопросы по тегам:

Похожие вопросы: