Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • GfG 160: Daily DSA
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Aptitude
  • Engineering Mathematics
  • Discrete Mathematics
  • Operating System
  • DBMS
  • Computer Networks
  • Digital Logic and Design
  • C Programming
  • Data Structures
  • Algorithms
  • Theory of Computation
  • Compiler Design
  • Computer Org and Architecture
Open In App
Next Article:
Program for SSTF Disk Scheduling Algorithm
Next article icon

Program for SSTF Disk Scheduling Algorithm

Last Updated : 20 Sep, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array of disk track numbers and initial head position, our task is to find the total number of seek operations done to access all the requested tracks if Shortest Seek Time First (SSTF) is a disk scheduling algorithm is used.

The basic idea is the tracks that are closer to the current disk head position should be serviced first in order to minimize the seek operations is basically known as Shortest Seek Time First (SSTF).

Advantages of Shortest Seek Time First (SSTF)

  • Better performance than the FCFS scheduling algorithm.
  • It provides better throughput.
  • This algorithm is used in Batch Processing systems where throughput is more important.
  • It has a less average response and waiting time.

Disadvantages of Shortest Seek Time First (SSTF)

  • Starvation is possible for some requests as it favours easy-to-reach requests and ignores the far-away processes.
  • There is a lack of predictability because of the high variance of response time.
  • Switching direction slows things down.

Algorithm

Step 1: Let the Request array represents an array storing indexes of tracks that have been requested. 'head' is the position of the disk head.

Step 2: Find the positive distance of all tracks in the request array from the head.

Step 3: Find a track from the requested array which has not been accessed/serviced yet and has a minimum distance from the head.

Step 4: Increment the total seek count with this distance.

Step 5: Currently serviced track position now becomes the new head position.

Step 6: Go to step 2 until all tracks in the request array have not been serviced. 

Example:

Request sequence = {176, 79, 34, 60, 92, 11, 41, 114} 
Initial head position = 50 

The following chart shows the sequence in which requested tracks are serviced using SSTF.

Therefore, the total seek count is calculated as: 

SSTF (Shortest Seek Time First)
SSTF (Shortest Seek Time First)
= (50-41)+(41-34)+(34-11)+(60-11)+(79-60)+(92-79)+(114-92)+(176-114)
= 204
which can also be directly calculated as: (50-11) + (176-11)

Implementation

The implementation of SSTF is given below. Note that we have made a node class having 2 members. ‘distance’ is used to store the distance between the head and the track position. ‘accessed’ is a boolean variable that tells whether the track has been accessed/serviced before by the disk head or not. 

C++
// C++ program for implementation of 
// SSTF disk scheduling
#include 
using namespace std;

// Calculates difference of each  
// track number with the head position 
void calculatedifference(int request[], int head,
                         int diff[][2], int n)
{
    for(int i = 0; i < n; i++)
    {
        diff[i][0] = abs(head - request[i]);
    }
}

// Find unaccessed track which is 
// at minimum distance from head 
int findMIN(int diff[][2], int n)
{
    int index = -1;
    int minimum = 1e9;
  
    for(int i = 0; i < n; i++)
    {
        if (!diff[i][1] && minimum > diff[i][0])
        {
            minimum = diff[i][0];
            index = i;
        }
    }
    return index;
}

void shortestSeekTimeFirst(int request[], 
                           int head, int n)
{
    if (n == 0)
    {
        return;
    }
    
    // Create array of objects of class node    
    int diff[n][2] = { { 0, 0 } };
    
    // Count total number of seek operation   
    int seekcount = 0;
    
    // Stores sequence in which disk access is done 
    int seeksequence[n + 1] = {0};
    
    for(int i = 0; i < n; i++)
    {
        seeksequence[i] = head;
        calculatedifference(request, head, diff, n);
        int index = findMIN(diff, n);
        diff[index][1] = 1;
        
        // Increase the total count 
        seekcount += diff[index][0]; 
        
        // Accessed track is now new head 
        head = request[index];
    }
    seeksequence[n] = head;
    
    cout << "Total number of seek operations = "
         << seekcount << endl;
    cout << "Seek sequence is : " << "\n";
    
    // Print the sequence 
    for(int i = 0; i <= n; i++) 
    {
        cout << seeksequence[i] << "\n";
    }
}

// Driver code
int main()
{
    int n = 8;
    int proc[n] = { 176, 79, 34, 60, 92, 11, 41, 114 };
    
    shortestSeekTimeFirst(proc, 50, n);
    
    return 0;
}

// This code is contributed by manish19je0495
Java
// Java program for implementation of 
// SSTF disk scheduling
class node {
    
    // represent difference between 
    // head position and track number
    int distance = 0; 
    
    // true if track has been accessed
    boolean accessed = false; 
}

public class SSTF {
    
    // Calculates difference of each 
    // track number with the head position
    public static void calculateDifference(int queue[], 
                                        int head, node diff[])
                                        
    {
        for (int i = 0; i < diff.length; i++)
            diff[i].distance = Math.abs(queue[i] - head);
    }

    // find unaccessed track 
    // which is at minimum distance from head
    public static int findMin(node diff[])
    {
        int index = -1, minimum = Integer.MAX_VALUE;

        for (int i = 0; i < diff.length; i++) {
            if (!diff[i].accessed && minimum > diff[i].distance) {
                
                minimum = diff[i].distance;
                index = i;
            }
        }
        return index;
    }

    public static void shortestSeekTimeFirst(int request[], 
                                                     int head)
                                                     
    {
        if (request.length == 0)
            return;
            
        // create array of objects of class node    
        node diff[] = new node[request.length]; 
        
        // initialize array
        for (int i = 0; i < diff.length; i++) 
        
            diff[i] = new node();
        
        // count total number of seek operation    
        int seek_count = 0; 
        
        // stores sequence in which disk access is done
        int[] seek_sequence = new int[request.length + 1]; 
        
        for (int i = 0; i < request.length; i++) {
            
            seek_sequence[i] = head;
            calculateDifference(request, head, diff);
            
            int index = findMin(diff);
            
            diff[index].accessed = true;
            
            // increase the total count
            seek_count += diff[index].distance; 
            
            // accessed track is now new head
            head = request[index]; 
        }
        
        // for last accessed track
        seek_sequence[seek_sequence.length - 1] = head; 
        
        System.out.println("Total number of seek operations = " 
                                                     + seek_count);
                                                     
        System.out.println("Seek Sequence is");
        
        // print the sequence
        for (int i = 0; i < seek_sequence.length; i++) 
            System.out.println(seek_sequence[i]);
    }

    public static void main(String[] args)
    {
        // request array
        int arr[] = { 176, 79, 34, 60, 92, 11, 41, 114 }; 
        shortestSeekTimeFirst(arr, 50);
    }
}
Python3
# Python3 program for implementation of 
# SSTF disk scheduling 

# Calculates difference of each 
# track number with the head position
def calculateDifference(queue, head, diff):
    for i in range(len(diff)):
        diff[i][0] = abs(queue[i] - head) 
    
# find unaccessed track which is 
# at minimum distance from head 
def findMin(diff): 

    index = -1
    minimum = 999999999

    for i in range(len(diff)):
        if (not diff[i][1] and 
                minimum > diff[i][0]):
            minimum = diff[i][0]
            index = i
    return index 
    
def shortestSeekTimeFirst(request, head):             
        if (len(request) == 0): 
            return
        
        l = len(request) 
        diff = [0] * l
        
        # initialize array 
        for i in range(l):
            diff[i] = [0, 0]
        
        # count total number of seek operation     
        seek_count = 0
        
        # stores sequence in which disk 
        # access is done 
        seek_sequence = [0] * (l + 1) 
        
        for i in range(l): 
            seek_sequence[i] = head 
            calculateDifference(request, head, diff) 
            index = findMin(diff) 
            
            diff[index][1] = True
            
            # increase the total count 
            seek_count += diff[index][0] 
            
            # accessed track is now new head 
            head = request[index] 
    
        # for last accessed track 
        seek_sequence[len(seek_sequence) - 1] = head 
        
        print("Total number of seek operations =", 
                                       seek_count) 
                                                        
        print("Seek Sequence is") 
        
        # print the sequence 
        for i in range(l + 1):
            print(seek_sequence[i]) 
    
# Driver code 
if __name__ =="__main__":
    
    # request array 
    proc = [176, 79, 34, 60, 
            92, 11, 41, 114]
    shortestSeekTimeFirst(proc, 50)
    
# This code is contributed by
# Shubham Singh(SHUBHAMSINGH10)
C#
// C# program for implementation of 
// SSTF disk scheduling
using System;
    
public class node
{
    
    // represent difference between 
    // head position and track number
    public int distance = 0; 
    
    // true if track has been accessed
    public Boolean accessed = false; 
}

public class SSTF 
{
    
    // Calculates difference of each 
    // track number with the head position
    public static void calculateDifference(int []queue, 
                                        int head, node []diff)
                                        
    {
        for (int i = 0; i < diff.Length; i++)
            diff[i].distance = Math.Abs(queue[i] - head);
    }

    // find unaccessed track 
    // which is at minimum distance from head
    public static int findMin(node []diff)
    {
        int index = -1, minimum = int.MaxValue;

        for (int i = 0; i < diff.Length; i++)
        {
            if (!diff[i].accessed && minimum > diff[i].distance)
            {
                
                minimum = diff[i].distance;
                index = i;
            }
        }
        return index;
    }

    public static void shortestSeekTimeFirst(int []request, 
                                                    int head)
    {
        if (request.Length == 0)
            return;
            
        // create array of objects of class node 
        node []diff = new node[request.Length]; 
        
        // initialize array
        for (int i = 0; i < diff.Length; i++) 
        
            diff[i] = new node();
        
        // count total number of seek operation 
        int seek_count = 0; 
        
        // stores sequence in which disk access is done
        int[] seek_sequence = new int[request.Length + 1]; 
        
        for (int i = 0; i < request.Length; i++)
        {
            
            seek_sequence[i] = head;
            calculateDifference(request, head, diff);
            
            int index = findMin(diff);
            
            diff[index].accessed = true;
            
            // increase the total count
            seek_count += diff[index].distance; 
            
            // accessed track is now new head
            head = request[index]; 
        }
        
        // for last accessed track
        seek_sequence[seek_sequence.Length - 1] = head; 
        
        Console.WriteLine("Total number of seek operations = "
                                                    + seek_count);
                                                    
        Console.WriteLine("Seek Sequence is");
        
        // print the sequence
        for (int i = 0; i < seek_sequence.Length; i++) 
            Console.WriteLine(seek_sequence[i]);
    }

    // Driver code
    public static void Main(String[] args)
    {
        // request array
        int []arr = { 176, 79, 34, 60, 92, 11, 41, 114 }; 
        shortestSeekTimeFirst(arr, 50);
    }
}

// This code contributed by Rajput-Ji
JavaScript
// Javascript Program for implementation of 
// SSTF disk scheduling
function calculatedifference(request, head, diff, n) {
    for (let i = 0; i < n; i++) {
        diff[i][0] = Math.abs(head - request[i]);
    }
}

// Find unaccessed track which is 
// at minimum distance from head 
function findMIN(diff, n) {
    let index = -1;
    let minimum = 1e9;

    for (let i = 0; i < n; i++) {
        if (!diff[i][1] && minimum > diff[i][0]) {
            minimum = diff[i][0];
            index = i;
        }
    }
    return index;
}

function shortestSeekTimeFirst(request, head, n) {
    if (n == 0) {
        return;
    }

    // Create array of objects of class node    
    let diff = new Array(n);
    for (let i = 0; i < n; i++) {
        diff[i] = new Array(2);
    }

    // Count total number of seek operation   
    let seekcount = 0;

    // Stores sequence in which disk access is done 
    let seeksequence = new Array(n + 1);
    seeksequence[0] = head;

    for (let i = 0; i < n; i++) {
        calculatedifference(request, head, diff, n);
        let index = findMIN(diff, n);
        diff[index][1] = 1;

        // Increase the total count 
        seekcount += diff[index][0];

        // Accessed track is now new head 
        head = request[index];
        seeksequence[i + 1] = head;
    }

    console.log("Total number of seek operations = " + seekcount);
    console.log("Seek sequence is : ");

    // Print the sequence 
    for (let i = 0; i <= n; i++) {
        console.log(seeksequence[i]);
    }
}

// Driver code
let n = 8;
let proc = [176, 79, 34, 60, 92, 11, 41, 114];

shortestSeekTimeFirst(proc, 50, n);

//  This code is contributed by ishankhandelwals.

Output

Total number of seek operations = 204
Seek Sequence: 50, 41, 34, 11, 60, 79, 92, 114, 176

Time Complexity: O(N^2)

Auxiliary Space: O(N) 


Next Article
Program for SSTF Disk Scheduling Algorithm

U

ujjwal rawat 1
Improve
Article Tags :
  • Misc
  • Operating Systems
Practice Tags :
  • Misc

Similar Reads

    Program for HRRN CPU Scheduling Algorithm
    The Highest Response Ratio Next (HRRN) scheduling algorithm is a non-preemptive scheduling technique used in operating systems to manage the execution of processes. It is designed to improve upon simpler algorithms like First-Come-First-Serve (FCFS) and Shortest Job Next (SJN) by balancing both the
    15 min read
    LOOK Disk Scheduling Algorithm
    The LOOK Disk Scheduling Algorithm is the advanced version of the SCAN (elevator) disk scheduling algorithm which gives slightly better seek time than any other algorithm in the hierarchy (FCFS->SRTF->SCAN->C-SCAN->LOOK). It is used to reduce the amount of time it takes to access data on
    13 min read
    FScan disk scheduling algorithm
    Fixed period SCAN (FSCAN) disk scheduling algorithm mainly focuses on handling high variance in shortest seek time first (SSTF). SCAN algorithm is also proposed to handle above mentioned situation but using SCAN algorithm causes long delay while handling requests which are at extremes of disk. FSCAN
    3 min read
    Disk Scheduling Algorithms
    Disk scheduling algorithms are crucial in managing how data is read from and written to a computer's hard disk. These algorithms help determine the order in which disk read and write requests are processed, significantly impacting the speed and efficiency of data access. Common disk scheduling metho
    12 min read
    FCFS Disk Scheduling Algorithms
    Prerequisite: Disk scheduling algorithms.Given an array of disk track numbers and initial head position, our task is to find the total number of seek operations done to access all the requested tracks if First Come First Serve (FCFS) disk scheduling algorithm is used. First Come First Serve (FCFS) F
    6 min read
    SCAN (Elevator) Disk Scheduling Algorithms
    In the SCAN Disk Scheduling Algorithm, the head starts from one end of the disk and moves towards the other end, servicing requests in between one by one and reaching the other end. Then the direction of the head is reversed and the process continues as the head continuously scans back and forth to
    12 min read
    C-SCAN Disk Scheduling Algorithm
    Given an array of disk track numbers and initial head position, our task is to find the total number of seek operations to access all the requested tracks if a C-SCAN Disk Scheduling algorithm is used.The Circular SCAN (C-SCAN) Scheduling Algorithm is a modified version of the SCAN Disk Scheduling A
    12 min read
    Program for FCFS CPU Scheduling | Set 1
    First come - First served (FCFS), is the simplest scheduling algorithm. FIFO simply queues processes according to the order they arrive in the ready queue. In this algorithm, the process that comes first will be executed first and next process starts only after the previous gets fully executed. Term
    15+ min read
    Difference between SSTF and LOOK disk scheduling algorithm
    Disk scheduling algorithms are used by operating systems to decide the order in which disk I/O requests are processed. Since disk access time is relatively slow, these algorithms aim to reduce the time it takes to read/write data by optimizing the movement of the disk arm.SSTF(Shortest Seek Time Fir
    3 min read
    Features of Global Scheduling Algorithm in Distributed System
    In this article, we will learn about the features of a good scheduling algorithm in a distributed system. Fault Tolerance:A good global scheduling algorithm should not be stopped when system nodes are crashed or temporarily crashed. Algorithm configuration should also be even if the nodes are separa
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

'); // $('.spinner-loading-overlay').show(); let script = document.createElement('script'); script.src = 'https://assets.geeksforgeeks.org/v2/editor-prod/static/js/bundle.min.js'; script.defer = true document.head.appendChild(script); script.onload = function() { suggestionModalEditor() //to add editor in suggestion modal if(loginData && loginData.premiumConsent){ personalNoteEditor() //to load editor in personal note } } script.onerror = function() { if($('.editorError').length){ $('.editorError').remove(); } var messageDiv = $('
').text('Editor not loaded due to some issues'); $('#suggestion-section-textarea').append(messageDiv); $('.suggest-bottom-btn').hide(); $('.suggestion-section').hide(); editorLoaded = false; } }); //suggestion modal editor function suggestionModalEditor(){ // editor params const params = { data: undefined, plugins: ["BOLD", "ITALIC", "UNDERLINE", "PREBLOCK"], } // loading editor try { suggestEditorInstance = new GFGEditorWrapper("suggestion-section-textarea", params, { appNode: true }) suggestEditorInstance._createEditor("") $('.spinner-loading-overlay:eq(0)').remove(); editorLoaded = true; } catch (error) { $('.spinner-loading-overlay:eq(0)').remove(); editorLoaded = false; } } //personal note editor function personalNoteEditor(){ // editor params const params = { data: undefined, plugins: ["UNDO", "REDO", "BOLD", "ITALIC", "NUMBERED_LIST", "BULLET_LIST", "TEXTALIGNMENTDROPDOWN"], placeholderText: "Description to be......", } // loading editor try { let notesEditorInstance = new GFGEditorWrapper("pn-editor", params, { appNode: true }) notesEditorInstance._createEditor(loginData&&loginData.user_personal_note?loginData.user_personal_note:"") $('.spinner-loading-overlay:eq(0)').remove(); editorLoaded = true; } catch (error) { $('.spinner-loading-overlay:eq(0)').remove(); editorLoaded = false; } } var lockedCasesHtml = `You can suggest the changes for now and it will be under 'My Suggestions' Tab on Write.

You will be notified via email once the article is available for improvement. Thank you for your valuable feedback!`; var badgesRequiredHtml = `It seems that you do not meet the eligibility criteria to create improvements for this article, as only users who have earned specific badges are permitted to do so.

However, you can still create improvements through the Pick for Improvement section.`; jQuery('.improve-header-sec-child').on('click', function(){ jQuery('.improve-modal--overlay').hide(); $('.improve-modal--suggestion').hide(); jQuery('#suggestion-modal-alert').hide(); }); $('.suggest-change_wrapper, .locked-status--impove-modal .improve-bottom-btn').on('click',function(){ // when suggest changes option is clicked $('.ContentEditable__root').text(""); $('.suggest-bottom-btn').html("Suggest changes"); $('.thank-you-message').css("display","none"); $('.improve-modal--improvement').hide(); $('.improve-modal--suggestion').show(); $('#suggestion-section-textarea').show(); jQuery('#suggestion-modal-alert').hide(); if(suggestEditorInstance !== null){ suggestEditorInstance.setEditorValue(""); } $('.suggestion-section').css('display', 'block'); jQuery('.suggest-bottom-btn').css("display","block"); }); $('.create-improvement_wrapper').on('click',function(){ // when create improvement option clicked then improvement reason will be shown if(loginData && loginData.isLoggedIn) { $('body').append('
'); $('.spinner-loading-overlay').show(); jQuery.ajax({ url: writeApiUrl + 'create-improvement-post/?v=1', type: "POST", contentType: 'application/json; charset=utf-8', dataType: 'json', xhrFields: { withCredentials: true }, data: JSON.stringify({ gfg_id: post_id }), success:function(result) { $('.spinner-loading-overlay:eq(0)').remove(); $('.improve-modal--overlay').hide(); $('.unlocked-status--improve-modal-content').css("display","none"); $('.create-improvement-redirection-to-write').attr('href',writeUrl + 'improve-post/' + `${result.id}` + '/', '_blank'); $('.create-improvement-redirection-to-write')[0].click(); }, error:function(e) { showErrorMessage(e.responseJSON,e.status) }, }); } else { if(loginData && !loginData.isLoggedIn) { $('.improve-modal--overlay').hide(); if ($('.header-main__wrapper').find('.header-main__signup.login-modal-btn').length) { $('.header-main__wrapper').find('.header-main__signup.login-modal-btn').click(); } return; } } }); $('.left-arrow-icon_wrapper').on('click',function(){ if($('.improve-modal--suggestion').is(":visible")) $('.improve-modal--suggestion').hide(); else{ } $('.improve-modal--improvement').show(); }); const showErrorMessage = (result,statusCode) => { if(!result) return; $('.spinner-loading-overlay:eq(0)').remove(); if(statusCode == 403) { $('.improve-modal--improve-content.error-message').html(result.message); jQuery('.improve-modal--overlay').show(); jQuery('.improve-modal--improvement').show(); $('.locked-status--impove-modal').css("display","block"); $('.unlocked-status--improve-modal-content').css("display","none"); $('.improve-modal--improvement').attr("status","locked"); return; } } function suggestionCall() { var editorValue = suggestEditorInstance.getValue(); var suggest_val = $(".ContentEditable__root").find("[data-lexical-text='true']").map(function() { return $(this).text().trim(); }).get().join(' '); suggest_val = suggest_val.replace(/\s+/g, ' ').trim(); var array_String= suggest_val.split(" ") //array of words var gCaptchaToken = $("#g-recaptcha-response-suggestion-form").val(); var error_msg = false; if(suggest_val != "" && array_String.length >=4){ if(editorValue.length <= 2000){ var payload = { "gfg_post_id" : `${post_id}`, "suggestion" : `${editorValue}`, } if(!loginData || !loginData.isLoggedIn) // User is not logged in payload["g-recaptcha-token"] = gCaptchaToken jQuery.ajax({ type:'post', url: "https://apiwrite.geeksforgeeks.org/suggestions/auth/create/", xhrFields: { withCredentials: true }, crossDomain: true, contentType:'application/json', data: JSON.stringify(payload), success:function(data) { if(!loginData || !loginData.isLoggedIn) { grecaptcha.reset(); } jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('.suggest-bottom-btn').css("display","none"); $('#suggestion-section-textarea').hide() $('.thank-you-message').css('display', 'flex'); $('.suggestion-section').css('display', 'none'); jQuery('#suggestion-modal-alert').hide(); }, error:function(data) { if(!loginData || !loginData.isLoggedIn) { grecaptcha.reset(); } jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('#suggestion-modal-alert').html("Something went wrong."); jQuery('#suggestion-modal-alert').show(); error_msg = true; } }); } else{ jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('#suggestion-modal-alert').html("Minimum 4 Words and Maximum Words limit is 1000."); jQuery('#suggestion-modal-alert').show(); jQuery('.ContentEditable__root').focus(); error_msg = true; } } else{ jQuery('.spinner-loading-overlay:eq(0)').remove(); jQuery('#suggestion-modal-alert').html("Enter atleast four words !"); jQuery('#suggestion-modal-alert').show(); jQuery('.ContentEditable__root').focus(); error_msg = true; } if(error_msg){ setTimeout(() => { jQuery('.ContentEditable__root').focus(); jQuery('#suggestion-modal-alert').hide(); }, 3000); } } document.querySelector('.suggest-bottom-btn').addEventListener('click', function(){ jQuery('body').append('
'); jQuery('.spinner-loading-overlay').show(); if(loginData && loginData.isLoggedIn) { suggestionCall(); return; } // script for grecaptcha loaded in loginmodal.html and call function to set the token setGoogleRecaptcha(); }); $('.improvement-bottom-btn.create-improvement-btn').click(function() { //create improvement button is clicked $('body').append('
'); $('.spinner-loading-overlay').show(); // send this option via create-improvement-post api jQuery.ajax({ url: writeApiUrl + 'create-improvement-post/?v=1', type: "POST", contentType: 'application/json; charset=utf-8', dataType: 'json', xhrFields: { withCredentials: true }, data: JSON.stringify({ gfg_id: post_id }), success:function(result) { $('.spinner-loading-overlay:eq(0)').remove(); $('.improve-modal--overlay').hide(); $('.create-improvement-redirection-to-write').attr('href',writeUrl + 'improve-post/' + `${result.id}` + '/', '_blank'); $('.create-improvement-redirection-to-write')[0].click(); }, error:function(e) { showErrorMessage(e.responseJSON,e.status); }, }); });
"For an ad-free experience and exclusive features, subscribe to our Premium Plan!"
Continue without supporting
`; $('body').append(adBlockerModal); $('body').addClass('body-for-ad-blocker'); const modal = document.getElementById("adBlockerModal"); modal.style.display = "block"; } function handleAdBlockerClick(type){ if(type == 'disabled'){ window.location.reload(); } else if(type == 'info'){ document.getElementById("ad-blocker-div").style.display = "none"; document.getElementById("ad-blocker-info-div").style.display = "flex"; handleAdBlockerIconClick(0); } } var lastSelected= null; //Mapping of name and video URL with the index. const adBlockerVideoMap = [ ['Ad Block Plus','https://media.geeksforgeeks.org/auth-dashboard-uploads/abp-blocker-min.mp4'], ['Ad Block','https://media.geeksforgeeks.org/auth-dashboard-uploads/Ad-block-min.mp4'], ['uBlock Origin','https://media.geeksforgeeks.org/auth-dashboard-uploads/ub-blocke-min.mp4'], ['uBlock','https://media.geeksforgeeks.org/auth-dashboard-uploads/U-blocker-min.mp4'], ] function handleAdBlockerIconClick(currSelected){ const videocontainer = document.getElementById('ad-blocker-info-div-gif'); const videosource = document.getElementById('ad-blocker-info-div-gif-src'); if(lastSelected != null){ document.getElementById("ad-blocker-info-div-icons-"+lastSelected).style.backgroundColor = "white"; document.getElementById("ad-blocker-info-div-icons-"+lastSelected).style.borderColor = "#D6D6D6"; } document.getElementById("ad-blocker-info-div-icons-"+currSelected).style.backgroundColor = "#D9D9D9"; document.getElementById("ad-blocker-info-div-icons-"+currSelected).style.borderColor = "#848484"; document.getElementById('ad-blocker-info-div-name-span').innerHTML = adBlockerVideoMap[currSelected][0] videocontainer.pause(); videosource.setAttribute('src', adBlockerVideoMap[currSelected][1]); videocontainer.load(); videocontainer.play(); lastSelected = currSelected; }

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences