简体   繁体   English

JavaScript代码执行延迟

[英]Javascript code execution delayed

I have called my below function on the click event. 我在点击事件上调用了以下函数。 Basically this code takes some time (approximately 200ms) to execute on the browser because of I am triggering click event on the jquery tree. 基本上,由于我要触发jquery树上的click事件,因此该代码需要一些时间(大约200毫秒)才能在浏览器上执行。

function showAsset()
{
      $(".err").html("Please wait . . .")
      $(".err").css('display','block')
      $(".err").css('background','orange')
      v=$("#asset_details").val()
      v=v.split("###")
      v1=v[0].split("-")
//Upto this block should be executed first

      //Jquery Tree block starts
      $("#navigation ."+v1+" div").click()
      $("#navigation ."+v[1]+" div").click()
      $("#navigation table tr:contains('"+v[0]+"')").css({'background':'#FFF82A'})
       $('html, body').animate({
        'scrollTop' :( $("#navigation table tr:contains('"+v[0]+"')").position().top-5)
    });
       //Jquery Tree block ends
}

So to instrut my users about this loading, I am showing "please wait . . ." 因此,要向我的用户介绍此负载,我正在显示“请稍候...”。 message at start of the function call. 函数调用开始时出现的消息。 But this message is showing after full execution of the function call. 但是,此消息在完全执行函数调用后显示。

My question is why the start of the block also gets delayed when i call this function. 我的问题是,当我调用此函数时,为什么块的开始也会延迟。 I placed the Jquery Tree block at the bottom of the function. 我将Jquery Tree块放在函数的底部。 But overall code is executed at the same time. 但是总体代码是同时执行的。

Is there any way to separate this execution. 有什么办法可以分开执行。

You can use setTimeout to separate your execution. 您可以使用setTimeout分隔执行。

Calls a function or executes a code snippet after a specified delay. 在指定的延迟后调用函数或执行代码段。

source 资源

The first block without setTimeout is executed and after the setTimeout is executed in separate scope. 执行不带setTimeout的第一个块,然后在单独的范围内执行setTimeout之后。

function showAsset() {
  $(".err").html("Please wait . . .")
  $(".err").css('display', 'block')
  $(".err").css('background', 'orange')
  v = $("#asset_details").val()
  v = v.split("###")
  v1 = v[0].split("-")
    //Upto this block should be executed first

  //Jquery Tree block starts

  setTimeout(function() {
    $("#navigation ." + v1 + " div").click()
    $("#navigation ." + v[1] + " div").click()
    $("#navigation table tr:contains('" + v[0] + "')").css({
      'background': '#FFF82A'
    })
    $('html, body').animate({
      'scrollTop': ($("#navigation table tr:contains('" + v[0] + "')").position().top - 5)
    });
    //Jquery Tree block ends
  }, 0);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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