23 Nov 2012

DELAY, SLEEP, PAUSE, WAIT ETC IN JAVASCRIPT


Today I was just looking into ways to simulate delay, sleep, pause, wait or such in JavaScript/jQuery. I’ve briefly looked into this topic before for locking a web page on timer. Here are some more thoughts on the topic. PHP has a sleep() function but JavaScript doesn’t as such. jQuery offers us both setTimeout which is similar to run a block of code after a specific time period. Well, this is because it’s useless you might say. But for simulating heavy processing and for misc performance measurements, it could be useful. So here’s how you can go about creating a sleep() in JavaScript, just a little code snippet I found somewhere.

Example of sleep function in js

function sleep(milliseconds) {
  var start = new Date().getTime();
  for (var i = 0; i < 1e7; i++) {
    if ((new Date().getTime() - start) > milliseconds){
      break;
    }
  }
}

Usage

Sleep for 1 second (1000 milliseconds).
console.log(new Date());
console.log('Dude!');
sleep(1000);
console.log(new Date());

PHP to JS

Great project – essentially converting PHP function logic to JavaScript. I saw they have converted PHP’s < href="http://www.php.net/manual/en/function.time-sleep-until.php">time_sleep_until into JavaScript function below.
function time_sleep_until (timestamp) {
  // http://kevin.vanzonneveld.net
  // +   original by: Brett Zamir (http://brett-zamir.me)
  // %          note: For study purposes. Current implementation could lock up the user's browser.
  // %          note: Expects a timestamp in seconds, so DO NOT pass in a JavaScript timestamp which are in milliseconds (e.g., new Date()) or otherwise the function will lock up the browser 1000 times longer than probably intended.
  // %          note: Consider using setTimeout() instead.
  // *     example 1: time_sleep_until(1233146501) // delays until the time indicated by the given timestamp is reached
  // *     returns 1: true
  while (new Date() < timestamp * 1000) {}
  return true;
}

//run
time_sleep_until(1233146501) // delays until the time indicated by the given timestamp is reached

Other sleepy stuff

May you could use a chained delay() function?
- trigger function after x milliseconds $("#myElement").delay(2000).trigger("click");
Or a setTimeout()…
var dotCounter = 0;
(function addDot() {
  setTimeout(function() {
    if (dotCounter++ < 10) {
      $('#dots').append('.');
      addDot();
    }
  }, 1000);
})();

JQUERY SELECTOR FIRST X ITEMS OF SPECIFIC CLASS


I’ve been playing around with this a little. Grabbing a specific number of DOM elements based on a specified class.
First, basics to get the first and last elements like so:
var firstSpan = $('span.class:first'),
    lastSpan = $('span.class:last');
To get all the elements that match a specified class like so:
var allSpans = $('span.class').get();
or the nth/xth element like so:
var firstSpan = $('span.class').get(0),
    secondSpan = $('span.class').get(1);
    //etc...
But how to get say the first 10 elements or elements 10-20?
It would be nice to go something like:
var mySpans = $('span.class').get(0,10);
Unfortunately, the .get() function doesn’t allow for a range to be passed, but just a single index. So here is an attempt to use the jQuery .get() function to include a range of elements.
(function($)
{
  //function that gets a range of dom elements against a jQuery selector
  //returns an array of dom elements
  $.fn.getRange = function(start,end)
  {
    var elems = [];
    for ( var i = start; i <= end; i++ )
    {
      elems.push(this.get(i));
    }
    return elems;
  };

  //testing
  console.log($('div').getRange(1,10));
  console.log($('div').getRange(10,20));

})(jQuery);
Does anyone know of a better way to achieve this?

22 Nov 2012

Do something after paste using jquery


Example in jsFiddle: http://jsfiddle.net/VAT83/
$(function() {
    var textValue = $('#textValue');        
    $('#textareaID')
         .bind('input propertychange', function() {
             textValue.html($(this).val());
         })
         .trigger('propertychange');
});​

Intercept paste event in Javascript


You can intercept the paste event by attaching an "onpaste" handler and get the pasted text by using "window.clipboardData.getData('Text')" in IE or "event.clipboardData.getData('text/plain')" in other browsers.
For example:
var myElement = document.getElementById('pasteElement');
myElement.onpaste = function(e) {
  var pastedText = undefined;
  if (window.clipboardData && window.clipboardData.getData) { // IE
    pastedText = window.clipboardData.getData('Text');
  } else if (e.clipboardData && e.clipboardData.getData) {
    pastedText = e.clipboardData.getData('text/plain');
  }
  alert(pastedText); // Process and handle text...
  return false; // Prevent the default handler from running.
};
you will need to use "e.originalEvent.clipboardData" if using jQuery.