简体   繁体   中英

How to give a time delay in Visual Studio macros

Recently I updated my Visual Studio and start using the extention Macro Explorer.

I tried to use one of the sample macros "removes and sorts all", but I realized if I have a open documents, it doesn't run. So I closed all my open documents and try again this time it open all documents and close them but it doesn't work either.

The problem is the command executed before the document completely load. If there was a event or timer that can help wait until document load completely the problem will solve.

Here is my code. I marked where I want to add wait function:

function formatFile(file) {
    dte.ExecuteCommand("View.SolutionExplorer");
    if (file.Name.indexOf(".cs", file.Name.length - ".cs".length) !== -1) {
        file.Open();
        file.Document.Activate();

//here i want to wait for 1 second
        dte.ExecuteCommand("Edit.RemoveAndSort");

        file.Document.Save();
        file.Document.Close();
    }
}

I appreciate any sort of help.

Macro Explorer on GitHub: https://github.com/Microsoft/VS-Macros

According to the code snippet you shared in your original post and I also clone the project from GitHub, your code should be JavaScript code.

In JavaScript code, there has setTimeout() or setInterval() functions. For example, if you use setTimeout(), you need to move the code that you need to run after the pause into the setTimeout() callback.

Please modify your code as below.

function formatFile(file) {
dte.ExecuteCommand("View.SolutionExplorer");
if (file.Name.indexOf(".cs", file.Name.length - ".cs".length) !== -1) {
    file.Open();
    file.Document.Activate();


    setTimeout(function () {
        //move the code that you want to run after 1 second
        dte.ExecuteCommand("Edit.RemoveAndSort");
        file.Document.Save();
        file.Document.Close();
    }, 1000);

}

And there are lots of thread about sleep() in Javascript code. Please refer to:

What is the JavaScript version of sleep()?

JavaScript sleep/wait before continuing

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM