2017-06-16 166 views
1

太平幫助這裏的循環 - 但有沒有辦法停止運行後續代碼,直到循環完成後:Javascript代碼不是按順序運行

當我運行下面的代碼,我得到的提示進入我的名,下滾功能運行之前 - 但輸入提示的下滾碼AFTER:

function scrollDown(num_times) { 
 
    num_times -= 1; 
 
    if (num_times === 0) { 
 
    return; 
 
    } 
 
    window.scrollBy(0, 500); // horizontal and vertical scroll increments 
 
    setTimeout(function() { 
 
    scrollDown(num_times); 
 
    }, 500); 
 
} 
 
//This should run first and scroll the screen before prompting 
 
scrollDown(30); // scroll down 30 times 
 

 

 
//However this prompt comes up before the above code has ran 
 
var kw = prompt("Please enter your name");

任何意見,將不勝感激。

謝謝,馬克

+3

@FailedUnitTest:沒有,在JavaScript代碼運行** **同步,除非另有說明。 Promise回調函數和'setTimeout'回調函數都是「另外聲明」的東西。 –

+0

是的,你是對的。出於某種原因,我正在考慮ajax電話。 – FailedUnitTest

+0

您可能需要在提示符周圍使用標誌,類似於此問題:https://stackoverflow.com/questions/4122268/using-settimeout-synchronously-in-javascript – scrappedcola

回答

0
var kw; 

function scrollDown(num_times) { 
    if (num_times === 0) { 
    /* you can define your prompt after scrollDown has ended */ 
    kw = prompt("Please enter your name"); 
    return; 
    } 
    window.scrollBy(0, 500); 
    setTimeout(function() { 
    scrollDown(num_times - 1); 
    }, 500); 
} 

scrollDown(30); 
1

將代碼放在你最後一次滾動迭代後執行的回調。

function scrollDown(num_times, callback) { 
 
    if (num_times === 0) { 
 
    callback(); 
 
    } 
 
    window.scrollBy(0, 500); // horizontal and vertical scroll increments 
 
    setTimeout(function() { 
 
    scrollDown(num_times - 1, callback); 
 
    }, 500); 
 
} 
 
//This should run first and scroll the screen before prompting 
 
scrollDown(30, function() { 
 
    kw = prompt("Please enter your name"); 
 
    document.getElementById("result").textContent = kw; 
 
} 
 
); // scroll down 30 times
Your name is: <span id="result"></span>