Detect if any JavaScript function is running

前端 未结 3 939
离开以前
离开以前 2021-02-19 03:51

I know it may sound very strange, but I need to know if there is any active/running javascript in the page.

I am in situation in which I have to run my javascript/jquery

3条回答
  •  情歌与酒
    2021-02-19 04:29

    Create a loader

    Hi, as javaScript can run async functions or calls, I also needed a way to know when the page was in a stable state. For that purpose, I use a tiny loader in each one of my functions:

        var loading_var = 0;
    
        // some functions in your code that may not execute at the same time
        // or have to wait an async call
        function f1() {
          loading_var++;
          // code to be exectuted
          onready();
        }
    
        function f2() {
          loading_var++;
          // code to be exectuted
          onready();
        }
    
        // loader function
        function onready() {
          loading_var--;
          if(loading_var == 0) {
            // Means all functions have finished executing !
            }
        }
    

    I often couple it with a freezeClic function to prevent users to interact with the page when there is a script that is still waiting an ajax / async response (and optionnaly display a preloader icon or screen).

提交回复
热议问题