Skip to content

IV Javascript

Sandesh Kota edited this page Dec 6, 2019 · 23 revisions
  • Output ?
{
  // block scope
  {
    // nested block scope
    var a = 10;
    let b = 10;
    const c = 10;
  }
}

if(true) {
  // block scope
}

for (var i =1; i <= 10; i ++){
  // block scope
}

for (let j =1; j <= 10; j ++){
  // block scope
}

function sum(a, b) {
  // function scope
  var k = a + b;
}

console.log(k); // error: Uncaught ReferenceError: k is not defined
console.log(i);  // 11
console.log(j);  // error: Uncaught ReferenceError: j is not defined
console.log(a);  // 10
console.log(b);  // error: Uncaught ReferenceError: b is not defined
console.log(c);  // error: Uncaught ReferenceError: c is not defined
const timerId = setTimeout (
    () => console.log('No wati time'),
    0
);
clearTimeout(timerId);
setTimeout(
  () => console.log('Hello after 0.5 seconds!'),
  500
);

for(let i = 0; i < 1e10; i++) {
  // Some logic
}
  • Call a function every 2 second. Retry it only for 5 times

let i =0;
const timerId = setInterval (
    () => {
        i++;
        if(i == 5){
            console.log('clearing after 5 retries');
            clearInterval(timerId);
        }
        var result = LoadData();
        console.log(result);
        if(result == 'success'){
            console.log('clearing since it is a success');
            clearInterval(timerId);
        }
    },
    500
);


const LoadData = () => {
    // ajax call
    return 'failure';
}
  • Challenge 1

Print "Hello World" forever. Starting with a delay of 1 second but then incrementing the delay by 1 second each time. The second time will have a delay of 2 seconds The third time will have a delay of 3 seconds.

Include the delay in the printed message
Hello World. 1
Hello World. 2
Hello World. 3
...

Constraints: You can only use const (no let or var)

const timer = 1000;
function Print(timer){
  setTimeout(
    () =>{ 
      console.log('Hello World. ', timer/1000);
      Print(timer + 1000);
    },
    timer
  );
}

Print(timer);
  • Challenge 2

Just like Challenge 1 but this time with repeated delay values. Print Hello World 5 times with a delay of 100 ms. Then Print it again 5 more times with a delay of 200 ms. Then print it again 5 more times with a delay of 300 ms. And so on until the program is killed.

Include the delay in the printed message:
Hello World. 100
Hello World. 100
Hello World. 100
Hello World. 100
Hello World. 100
Hello World. 200
Hello World. 200
Hello World. 200
...

var timer = 1000;
var counter = 0;
function Print(timer){
  var looper = setInterval(
    () =>{ 
      console.log('Hello World. ', timer/1000);
      counter++;
      if(counter == 5){
        clearInterval(looper);
        counter = 1;
        timer = timer + 1000;
        Print(timer);
      }
    },
    timer
  );
}

Print(timer);

Clone this wiki locally