How can I perform an operation after that some time (a fraction of second) is passed in JQuery\JavaScript?

114 Views Asked by At

I have to perform an operation after a delay time (a fraction of a second).

Actually I have this code section:

$("thead.opening").click(function () {
    var is_chrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;

    alert("INTO second function, chrome: " + is_chrome);

    $(this).next().css('width', '10000000em');
    $(this).next().css('display', 'table-row-group');

});

What I need to do is replace this alert():

alert("INTO second function, chrome: " + is_chrome);

with an operation that wait some time.

How can I do it?

Thx

4

There are 4 best solutions below

2
Irvin Dominin On

Use a timeout; in javascript you can use setTimeout to:

Calls a function or executes a code snippet after a specified delay.

Like:

var is_chrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
var $myNext=$(this).next();

if (is_chrome) {
    window.setTimeout(function() {
         $myNext.css({width: '10000000em', display: 'table-row-group'});
    }, 1000);
}

Demo: http://jsfiddle.net/4pxedhzd/

Ref: https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setTimeout

2
Reeno On

Replace

alert("INTO second function, chrome: " + is_chrome);

with

if(is_chrome) {
    var that = this;
    window.setTimeout(function() {
        $(that).next().css({'width':'10000000em', 'display':'table-row-group'});
    }, 1000);
}

This will run the function after 1000 milliseconds (=1 second). You have to set that = this because this has another context in the function.

JSFiddle demo: https://jsfiddle.net/0eajx8sv/

1
Lukesoft On

You can use pure javascript function setTimeout

setTimeout(
  function() 
  {
    //Execute the code to be run
  }, 1000);

final Solution

$("thead.opening").click(function () {
    var is_chrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;


    setTimeout(
      function() 
      {
        //Execute the code to be run
    $(this).next().css('width', '10000000em');
    $(this).next().css('display', 'table-row-group');
      }, 1000);


});
0
ILOABN On

Instead of having a typical "wait" in the middle of your code I would suggest using callbacks since that's what JavaScript uses normally.

I would suggest using the "setTimeout" function to make the JavaScript call wait some specific time before doing the next things. Here's how it could be used in your scenario:

$("thead.opening").click(function () {
    var is_chrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;

    setTimout(waitedCall(), millisecondsToWait);
});

//This function will now be called after "millisecondsToWait" ms. And then execute the rest of the code
function waitedCall()
{
    $(this).next().css('width', '10000000em');
    $(this).next().css('display', 'table-row-group');
}